[英]Write dynamic filter for Entity Framework Core
I'm writing a small project use .net Core and Entity Framework. 我正在编写一个使用.net Core和Entity Framework的小型项目。
I need implement dynamic filter for IQueryable<T>
. 我需要为
IQueryable<T>
实现动态过滤器。
I have enums that define operators 我有定义运算符的枚举
public enum QueryOperatorEnums
{
Equal = 0,
NotEqual = 1,
Constant = 2,
LessThan = 3,
GreaterThan = 4,
LessThanOrEqual = 5,
GreaterThanOrEqual = 6,
}
And I have an extensions of IQueryable
: 而且我有
IQueryable
的扩展:
public static IQueryable<T> Filter<T>(this IQueryable<T> query, Dictionary<string, KeyValuePair<QueryOperatorEnums, object>> keyValuePairs)
{
if (keyValuePairs == null)
return query;
foreach (var keyValuePair in keyValuePairs)
{
var propertyInfo = typeof(T).GetProperty(keyValuePair.Key);
if (propertyInfo != null)
{
var operation = keyValuePair.Value;
switch (operation.Key)
{
case QueryOperatorEnums.Constant:
break;
case QueryOperatorEnums.Equal:
query = query.Where(obj => propertyInfo.GetValue(obj, null).Equals(operation.Value));
break;
case QueryOperatorEnums.GreaterThan:
break;
case QueryOperatorEnums.GreaterThanOrEqual:
break;
case QueryOperatorEnums.LessThan:
break;
case QueryOperatorEnums.LessThanOrEqual:
break;
case QueryOperatorEnums.NotEqual:
break;
default:
break;
}
}
}
return query;
} }
What can I do to implement for special cases? 在特殊情况下我该怎么做? Because property value is dynamic at run time.
因为属性值在运行时是动态的。 I can't detect type to use
<=
, >=
... 我无法检测到要使用
<=
, >=
...的类型
Thanks for your support 谢谢你的支持
As you have seen, you cannot use reflection. 如您所见,您不能使用反射。
However, 2 third-party libraries can help you with this 但是,有2个第三方库可以帮助您
https://www.nuget.org/packages/System.Linq.Dynamic.Core/ https://www.nuget.org/packages/System.Linq.Dynamic.Core/
The syntax required is a little bit different from C# but work great. 所需的语法与C#稍有不同,但效果很好。 It's the most popular library to do such a thing.
这是最受欢迎的图书馆。
Disclaimer : I'm the owner of the project C# Eval Expression 免责声明 :我是C#Eval Expression项目的所有者
The library is not free, but you can do pretty much any dynamic LINQ using the same syntax as C#. 该库不是免费的,但是您几乎可以使用与C#相同的语法来进行任何动态LINQ。
So you will be able to build a string to evaluate and the library will do the rest for you. 这样您就可以构建一个字符串来求值,而库将为您完成其余工作。
Here are some example using EF Classic: 以下是使用EF Classic的一些示例:
Has Dynamic linq work with MySql, Sql Server and Postgresql, Jonathan?
Dynamic linq是否可以与MySql,Sql Server和Postgresql,Jonathan一起使用?
Yes, I don't see why it could not work. 是的,我不明白为什么它不起作用。 Under the hood, is generate LINQ expression as you could call by hand.
在后台,您可以手动调用生成LINQ表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.