entity framework – 由同一列中的多个条件选择 – 引用表
示例场景:
两个表: order和orderItem ,关系一对多。
我想选择至少有一个orderItem的价格为100的订单和至少一个价格为200的orderItem的订单。我可以这样做:
var orders = (from o in kontextdbs.orders join oi in kontextdbs.order_item on o.id equals oi.order_id join oi2 in kontextdbs.order_item on o.id equals oi2.order_id where oi.price == 100 && oi2.price == 200 select o).Distinct();
但是,如果这些条件是用户生成的呢? 所以我不知道会有多少条件。
您需要使用Where
和Any
方法遍历所有值,如下所示:
List values= new List() { 100, 200 }; var orders = from o in kontextdbs.orders select o; foreach(int value in values) { int tmpValue = value; orders = orders.Where(x => kontextdbs.order_item.Where(oi => x.id == oi.order_id) .Any(oi => oi.price == tmpValue)); } orders = orders.Distinct();
List orderValues = new List() { 100, 200 }; ObjectQuery orders = kontextdbs.Orders; foreach(int value in orderValues) { orders = (ObjectQuery )(from o in orders join oi in kontextdbs.order_item on o.id equals oi.order_id where oi.price == value select o); } orders = orders.Distinct();
应该工作,或者至少是一般模式 – 你可以在每个阶段对IObjectQueryables应用额外的查询。
请注意,根据我的经验,使用EF生成这样的动态查询会带来糟糕的性能 – 不幸的是 – 它会在第一次获得特定模式时花费几秒钟将每个编译成SQL。 如果订单值的数量相当稳定,那么这个特定的查询应该可以正常工作。
- 如何在asp.net核心中获取项目的根目录。 Directory.GetCurrentDirectory()似乎无法在mac上正常工作
- 什么是XPS文件以及如何使用它们
- Microsoft Enterprise Library类型加载exception无法加载Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer
- 以编程方式从DataTable创建DataGridview
- 如何将PNG透明化为GDI32(在c#中)以与alphaBlend一起使用?
- 前缀(++ x)和后缀(x ++)操作如何工作?
- 使用.NET进行选择性FTP下载
- unit testingWindows 8 Store App UI(Xaml控件)
- Json.NET如何在反序列化期间执行dependency injection?