问题描述
我想知道使用实体框架和 linq 创建动态查询的最佳方式是什么.
I would like to know what is the best way of creating dynamic queries with entity framework and linq.
我想创建一个服务,该服务具有许多用于排序和过滤的参数(超过 50 个).我将从 gui 获取对象,这些对象将在其中填写...并且查询将从单个服务方法执行.
I want to create a service that has many parameters for sorting and filtering (over 50). I will be getting object from gui where these will be filled out... and query will be executed from a single service method.
我环顾四周,发现我可以动态创建一个字符串,该字符串可以在我的方法结束时执行.我非常不喜欢这种方式.有一个更好的方法吗?最好使用编译检查类型安全?
I looked around And I saw that I could dynamically create a string that can be executed at the end of my method. I don't like this way very much. Is there a better way to do this? Preferably type safe with compile check?
推荐答案
您可以逐步编写一个 IQueryable
.假设你有一个 FilterDefinition
类,它描述了用户想要如何过滤......
You could compose an IQueryable<T>
step by step. Assuming you have a FilterDefinition
class which describes how the user wants to filter ...
public class FilterDefinition
{
public bool FilterByName { get; set; }
public string NameFrom { get; set; }
public string NameTo { get; set; }
public bool FilterByQuantity { get; set; }
public double QuantityFrom { get; set; }
public double QuantityTo { get; set; }
}
...然后你可以像这样构建一个查询:
... then you could build a query like so:
public IQueryable<SomeEntity> GetQuery(FilterDefinition filter)
{
IQueryable<SomeEntity> query = context.Set<SomeEntity>();
// assuming that you return all records when nothing is specified in the filter
if (filter.FilterByName)
query = query.Where(t =>
t.Name >= filter.NameFrom && t.Name <= filter.NameTo);
if (filter.FilterByQuantity)
query = query.Where(t =>
t.Quantity >= filter.QuantityFrom && t.Quantity <= filter.QuantityTo);
return query;
}
这篇关于使用实体框架创建动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!