gunnerz gunnerz - 9 months ago 49
C# Question

LINQ 'AsEnumerable' and the Entity Framework

I am writing a LINQ query similar to the following:

var test = from o in dbcontext.Orders.AsEnumerable()
where o.ID==1
select new Order
Name = GetName(o.ID)

In order to call an external function within the LINQ query, I am using
within the query.

I understand that normally the query is not executed until an enumeration function like
, etc. is called. But here I am calling the enumeration within the query.

Can anyone tell me if it is considered bad practice to use
like this? Will it suffer in performance compared to calling
after creating the query?

Answer Source

I'd do

var ids = from o in dbcontext.Orders
          where o.ID==1
          select new { ID = o.ID }; 

var names = from i in ids.AsEnumerable()
            select new Order { Name = GetName(i.ID) };

i.e. do as much querying as possible in the database, and then only perform the ID-to-name transformation in C#.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download