如何重用实体框架查询(使用方法)?

San*_*ken 7 c# linq linq-to-entities entity-framework entity-framework-4

我正在尝试重用部分查询,因为它足够复杂,我想尽量避免代码重复.

似乎在调用查询中的任何方法时,您最终得到:

LINQ to Entities无法识别方法{X}方法,并且此方法无法转换为存储表达式

理想情况下我想做的是:

var q = from item in context.Items
        where item.SomeCondition == true
        select new {Item = item, Connections = GetConnections(item)};
Run Code Online (Sandbox Code Playgroud)

GetConnections是执行查询的方法item.我正在尝试重用(相当复杂的)查询GetConnections,但我不知道如何让它工作.

GetConnections的当前签名类似于:

IQuerable<Connection> GetConnections(MyItem item)
Run Code Online (Sandbox Code Playgroud)

Amy*_*y B 11

Expression<Func<Customer, CustomerWithRecentOrders>>
  GetCustomerWithRecentOrdersSelector()
{
  return c => new CustomerWithRecentOrders()
  {
    Customer = c,
    RecentOrders = c.Orders.Where(o => o.IsRecent)
  };
}
Run Code Online (Sandbox Code Playgroud)

然后......

var selector = GetCustomerWithRecentOrderSelector();
var q = myContext.Customers
  .Where(c => c.SomeCondition)
  .Select(selector);
Run Code Online (Sandbox Code Playgroud)

  • 当您没有“IQuerable&lt;Customer&gt;”而只有“Customer”时,您知道如何做同样的事情吗?这甚至可能吗? (2认同)