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

时间:2010-07-10 00:07:55

标签: c# linq entity-framework linq-to-entities 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)};

GetConnections是在item上执行查询的方法。我正在尝试重用GetConnections中的(相当复杂的)查询,但我不确定如何使其工作。

GetConnections的当前签名类似于:

IQuerable<Connection> GetConnections(MyItem item)

2 个答案:

答案 0 :(得分:11)

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

然后......

var selector = GetCustomerWithRecentOrderSelector();
var q = myContext.Customers
  .Where(c => c.SomeCondition)
  .Select(selector);

答案 1 :(得分:-1)

您的查询对我来说几乎是完美的。你绝对可以从查询中调用GetConnections(item);调用方法是合法的。但是,您还有另一个问题:必须使用成员名称创建匿名类型成员(没有这些名称,您将无法访问它们。)

以下查询为我编译好:

var q = from item in context.Items
        where item.SomeCondition == true
        select new {item = item, connections = GetConnections(item)};

请注意item =connections =添加select

但请注意,您的GetConnections()方法可能需要static(我的是;我不确定您是否意外地将其遗漏了)。