生成LinqToEntities其中声明取决于用户选择 [英] Generating LinqToEntities Where statement depending on the user selection
问题描述
我有用户界面,用户可以选择该列的网格列(如年龄)和运算符(小于,等于或大于)。
网格数据然后根据选择进行过滤。
我有一个从客户端的JSON中反序列化的类。
///< summary>
///用于减少网格结果的过滤器
///< / summary>
public class Filter
{
///< summary>
///列名称
///< / summary>
public string name;
公共字符串值;
public int @operator {private get;组;
public Operator Operator()
{
return(Operator)@operator;
}
}
public enum运算符
{
无= -1,
LesserThan = 0,
等于= 1 ,
GreaterThan = 2
}
由于自然动态添加新列为了过滤我想创建访问数据的通用解决方案。
我想避免有大量if / switch语句,如
$
{
if(operator == Operator.LesserThan )
{
query = entities.Where(o => o.Age< age);
}
else if(operator == Operator.GreaterThan)
{
query = entities.Where(o => o.Age> age);
}
等
break;
}
等
}
任何想法如何创建更为通用的解决方案?
更新
似乎有很多方法可以实现比十亿if语句更清晰的解决方案。现在我只需要比较不同的解决方案。
你可以使用动态LINQ 创建查询动态
编辑:
动态LINQ查询的示例如下所示,假设列名称网格与实体中的字段名称相同:
string queryString;
queryString = columnName;
if(operator == Operator.LesserThan)
{
queryString + =<;
}
else if(operator == Operator.GreaterThan)
{
queryString + =>;
}
等
queryString + = age.ToString(); //或使用绑定变量,没有尝试自己在动态LINQ
query = intites.Where(queryString);
I have user-interface where user can select grid column (like age) and operator (lesser than, equals or greater than) for that column.
Grid data is then filtered according to the selection.
I have a following classes that are deserialized from the JSON that is coming from the client.
/// <summary>
/// Filter for reducing grid results
/// </summary>
public class Filter
{
/// <summary>
/// Name of the column
/// </summary>
public string name;
public string value;
public int @operator { private get; set; }
public Operator Operator()
{
return (Operator) @operator;
}
}
public enum Operator
{
None = -1,
LesserThan = 0,
Equals = 1,
GreaterThan = 2
}
Due to the nature dynamically adding new columns for filtering I would like to create generic solution for accessing the data.
I would like avoid having huge amount if/switch statements like
switch(columnName)
{
case "age":
{
if(operator == Operator.LesserThan)
{
query = entities.Where(o => o.Age < age);
}
else if (operator == Operator.GreaterThan)
{
query = entities.Where(o => o.Age > age);
}
etc.
break;
}
etc.
}
Any ideas how to create more generic solution for the problem?
Update It seems that there many ways to accomplish cleaner solution than one billion if statements. Now I just need to compare different solutions.
You could use Dynamic LINQ to create the query dynamically
Edit:
An example for Dynamic LINQ query would look like this, assuming that the column names in the grid are the same as the field names in the entity:
string queryString;
queryString = columnName;
if(operator == Operator.LesserThan)
{
queryString += " < ";
}
else if (operator == Operator.GreaterThan)
{
queryString += " > ";
}
etc.
queryString += age.ToString(); // Or use bind variables, haven't tried that myself in dynamic LINQ
query = entites.Where(queryString);
这篇关于生成LinqToEntities其中声明取决于用户选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!