4

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?

DavidRR
  • 18,291
  • 25
  • 109
  • 191
gunnerz
  • 1,898
  • 5
  • 24
  • 39
  • 1
    Worth Reading: https://stackoverflow.com/questions/10110266/why-linq-to-entities-does-not-recognize-the-method-system-string-tostring/43262421#43262421 – LCJ Jun 20 '17 at 21:02

1 Answers1

5

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

Rawling
  • 49,248
  • 7
  • 89
  • 127
  • 1
    In principal yes but, only if the type exposed by `dbContext.Orders` implements `IEnumerable` in s superior way to the standard `IEnumerable` extension. Since its not clear what type `dbContext.Orders` is, I can't say. – Jodrell Aug 15 '12 at 11:10