我正在尝试重用部分查询,因为它足够复杂,我想尽量避免代码重复。
似乎在调用查询中的任何方法时,最终得到:
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)
答案 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
(我的是;我不确定您是否意外地将其遗漏了)。