或许还有更好的办法。
我正在为nhibernate构建一个动态查询生成器,我们不想将hql直接放到应用程序中,我们希望它尽可能不依赖orm。目前看来:

  public override IEnumerable<T> SelectQuery(Dictionary<string, string> dictionary)
    {
        string t = Convert.ToString(typeof (T).Name);
        string criteria = string.Empty;
        foreach (KeyValuePair<string, string> item in dictionary)
        {
            if (criteria != string.Empty)
                  criteria += " and ";


            criteria += item.Key + " = '" + item.Value + "'";
        }

        string query = " from " + t;

        if (criteria != string.Empty)
            query += " where " + criteria;

        return FindByHql(query);
    }

好吧,很好,但是…这里有两个问题:
这个查询只处理“and”,我最初的想法是通过构建一个方法来动态构建字典,该字典接受属性名、值和运算符“and”或“or”,并与运算符数组一起构建字典。听起来是不是应该这样做?
好的,这很好,但是,当有一个整数时,它会因为单引号而失败。我认为最好的方法是让字典接受<T.Property, string>,然后反射到t.property中,以找到数据类型并相应地执行操作。我是不是太复杂了?
谢谢您。

最佳答案

像这样的怎么样?
其中有操作的枚举。不是为字典传递字符串,而是传递具有值类型和值操作的QueryObject类型。你可以看到下面。

public enum Operation
{
    And,
    Or
}

public class QueryObject
{
    public string Value { get; set; }
    public Type Type { get; set; }
    public Operation Operation { get; set; }
}

public override IEnumerable<T> SelectQuery(Dictionary<string, QueryObject> dictionary)
{
    string t = Convert.ToString(typeof(T).Name);
    string criteria = string.Empty;
    foreach (KeyValuePair<string, QueryObject> item in dictionary)
    {
        if (!string.IsNullOrEmpty(criteria))
        {
            switch (item.Value.Operation)
            {
                case Operation.And:
                    criteria += " and ";
                    break;
                case Operation.Or:
                    criteria += " or ";
                    break;
                default:
                    break;
            }
        }

        if (item.Value.Type == typeof(int))
        {
            criteria += item.Key + " = " + item.Value + " ";
        }
        else
        {
            criteria += item.Key + " = '" + item.Value + "'";
        }
    }

    string query = " from " + t;

    if (criteria != string.Empty)
        query += " where " + criteria;

    return FindByHql(query);
}

09-08 02:19
查看更多