gunnerz
gunnerz

Reputation: 1926

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 AsEnumerable() within the query.

I understand that normally the query is not executed until an enumeration function like ToList(), 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 AsEnumerable() like this? Will it suffer in performance compared to calling ToList() after creating the query?

Upvotes: 4

Views: 1773

Answers (1)

Rawling
Rawling

Reputation: 50174

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

Upvotes: 5

Related Questions