views:

98

answers:

3

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)
A: 

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

Shirik
It's not the compilation that fails, it's the execution. I didn't copy/paste the code in, but typed it by head instead, that's why I forgot the anonymous type members
Sander Rijken
+1  A: 
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);
David B
Any idea how to do the same thing when you don't have an `IQuerable<Customer>` but just `Customer`? Is that even possible?
Sander Rijken
CustomerWithRecentOrders x = myContext.Customers .Where(c => c == myCustomer) .Select(selector).Single()
David B
A: 

Can u share the actual implementation of the method

IQuerable GetConnections(MyItem item)

zeeshanhirani
My question is how a thing like this could be implemented, because any implementation that's done as `IQueryable<T> GetConnections(MyItem item)` will fail
Sander Rijken