How can I reuse Entity Framework queries (using methods)?

I am trying to reuse part of the request because it is complex enough so that I try to avoid code duplication.

It seems that when you call any method inside the request, you get:

LINQ to Entities does not recognize the method of the {X} method and this method cannot be translated.

Ideally, I would like to use:

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

GetConnections is a method that executes requests for item . I'm trying to reuse a (rather complicated) request in GetConnections , but I'm not sure how to make this work.

The current GetConnections signature looks something like this:

 IQuerable<Connection> GetConnections(MyItem item) 
+7
c # linq linq-to-entities entity-framework entity-framework-4
source share
2 answers
 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); 
+11
source share

Your request looks almost perfect to me. You can, of course, call GetConnections(item) from your request; calling methods are legal. However, you have one more problem: members of an anonymous type must be created with the names of the participants (without these names you would not have access to 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 select .

Please note, however, that your GetConnections () method may need to be static (mine was, I wasn’t sure that you accidentally ruled this out).

-one
source share

All Articles