How can Entity Framework queries be reused (using methods)?
I'm trying to reuse part of a query, because it's complex enough that I want to try to avoid code dupl开发者_如何转开发ication.
It seems that when calling any method inside a query, you end up with:
LINQ to Entities does not recognize the method {X} method, and this method cannot be translated into a store expression
What I would like to do ideally is use:
var q = from item in context.Items
where item.SomeCondition == true
select new {Item = item, Connections = GetConnections(item)};
GetConnections
is the method that performs queries on item
. I'm trying to reuse the (rather complex) query in GetConnections
, but I'm not sure how to get this to work.
Current signature of GetConnections is something like:
IQuerable<Connection> GetConnections(MyItem item)
Expression<Func<Customer, CustomerWithRecentOrders>>
GetCustomerWithRecentOrdersSelector()
{
return c => new CustomerWithRecentOrders()
{
Customer = c,
RecentOrders = c.Orders.Where(o => o.IsRecent)
};
}
Then later...
var selector = GetCustomerWithRecentOrderSelector();
var q = myContext.Customers
.Where(c => c.SomeCondition)
.Select(selector);
Your query looks almost perfect to me. You can most certainly call GetConnections(item)
from within you query; calling methods is legal. However, you have another issue: Anonymous type members must be created with member names (without those names, you would have no way to access them).
The following query compiles fine for me:
var q = from item in context.Items
where item.SomeCondition == true
select new {item = item, connections = GetConnections(item)};
Note the addition of item =
and connections =
to the select
.
Please note, however, that your GetConnections() method may need to be static
(mine was; I wasn't sure if you left that out accidentally or not).
精彩评论