创建可重用的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
IQueryable
或IOrderedQueryable
)
如果where
filter是简单标量,则另一种方法是在数据库上下文的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)); } }
然后使用它像:
上述就是C#学习教程:创建可重用的Linq查询分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
var context = new MyContext(); var jedis = context.Customers.GetByName("skywalker"); if(jedis.Any()) { logger.Log("These aren't the customers you're looking for"); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1016947.html