7

我试图重用查询的一部分,因为它足够复杂,我想尽量避免代码重复。实体框架查询如何重用(使用方法)?

看来,调用查询内的任何方法时,你结束了:

LINQ到实体不承认 方法{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) 

回答

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

任何想法如果您没有'IQuerable '而只是'Customer '?这甚至可能吗? – 2010-07-13 08:28:45

+0

CustomerWithRecentOrders x = myContext.Customers .Where(c => c == myCustomer).Select(selector).Single() – 2010-07-13 12:48:34

-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(我是;我不确定是否意外地将它遗漏了)。

+0

这不是失败的汇编,它的执行。我没有复制/粘贴代码,而是通过头部键入代码,这就是为什么我忘记了匿名类型成员 – 2010-07-10 22:14:19