创建具有实体框架动态查询 [英] Creating dynamic queries with entity framework
问题描述
我想知道什么是创造与实体框架和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.
我环顾四周,我看到了,我可以动态创建,可在我的方法结束时执行的字符串。我不喜欢这种方式非常多。有没有更好的方式来做到这一点? preferably型与编译检查安全吗?
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< T>一步
一步。假设你有一个描述用户希望如何筛选 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;
}
这篇关于创建具有实体框架动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!