创建可重用的Linq查询

我有一个选择查询,反复使用不同的filter:

 var query = from row in context.Table select row; 

如何将其保存到静态类变量中,以便可以在不同的方法中重用它? 喜欢:

 var results1 = query.Where(condition1); ... var results2 = query.Where(condition2); 

你走在正确的轨道上。

考虑创建一个新方法而不是变量:

 public IQueryable ListActiveCustomers() { return dataContext.Customers.Where(c=>c.IsActive==true); } 

然后,您可以从方法可见的任何位置使用它:

  //Active Customers with no invoices due. var activePaidCustomers = ListActiveCustomers().Where(c=>c.InvoicesDue==0) .OrderByDescending(c=>c.LastPaidOn) .ToList(); 

像这样的东西:

 Expression> query = p => p.Value == someValue; // etc.. 

然后你可以执行以下操作,其中TypeYoureQueryingAgainst位于存储库或您正在使用的任何模式中:

 repository.Where(query); 

希望有意义..

这段代码:

 var query = from row in context.Table select row; 

在function上等同于:

 var query = context.Table; 

所以你不需要保持这个query变量来重用它,只需直接使用context.Table

 var results1 = context.Table.Where(condition1); ... var results2 = context.Table.Where(condition2); 

只需用IEnumerable (或IQueryable )替换var ,其中RowType是结果序列中每个项目的(非匿名)类型:

 static IEnumerable query = from ... select row; // row is of RowType. 

那么,第一步是找出确切的query类型。 最简单的方法是在调试器中使用它来逐步执行代码,看看它的类型是什么(可能是IQueryable IOrderedQueryable IQueryableIOrderedQueryable

如果wherefilter是简单标量,则另一种方法是在数据库上下文的DbSet属性上创建扩展方法。

如果你的DbContext是这样的:

 public class MyContext : DbContext { ... public DbSet Customers { get;set; } ... } 

您可以在Customers DbSet上创建可重用的查询,如:

 public static class MyDbContextExtension { public static IEnumerable GetByName(this DbSet customers, string name) { return customers.Where(c => c.Name.Contains(name)); } } 

然后使用它像:

 var context = new MyContext(); var jedis = context.Customers.GetByName("skywalker"); if(jedis.Any()) { logger.Log("These aren't the customers you're looking for"); }