Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 duplication.

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)
like image 474
Sander Rijken Avatar asked Jul 10 '10 00:07

Sander Rijken


1 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);
like image 115
Amy B Avatar answered Sep 23 '22 06:09

Amy B