Sar*_*pps 5 .net c# nhibernate orm .net-3.5
或者可能有更好的方法.
我正在为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);
}
Run Code Online (Sandbox Code Playgroud)
好的,很棒,但是......这里有两件事会造成问题:
这个查询只处理"和",我最初的想法是通过构建一个方法来动态构建带有属性名称,值和运算符"和"或"或"的字典,并与数组一起构建字典运营商.这听起来像是正确的事吗?
好的,所以,这很有效,但是,当有一个整数时,由于单引号而失败.我认为最好的方法是让字典接受<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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
243 次 |
| 最近记录: |