Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First IQueryable

I am using Entity Framework Code First and ran into a small road block. I have a class "Person" defined as such:

public class Person
{
    public Guid Id { get; set; }
    public virtual ICollection<History> History { get; set; }
}

and a class "History" defined as such:

public class History
{
    public Guid Id { get; set; }
    public virtual Person Owner { get; set; }
    public DateTime OnDate { get; set; }
}

However, when I call:

IEnumerable<History> results = person.History
                               .OrderBy(h => h.OnDate)
                               .Take(50)
                               .ToArray();

It appears to pull all of the history for the person, then order it and such in memory. Any recommendations on what I'm missing?

Thanks in advance!

like image 313
Terry Avatar asked Jun 24 '11 15:06

Terry


People also ask

Is IQueryable faster than IEnumerable?

IQueryable is faster than IEnumerable. In addition to Munesh Sharma's answer:IEnumerable loads data in-memory and then apply filters to it one by one but IQueryable apply filters all at once and return the result.

Do we need EDMX XML file for EF Code First approach?

Code first approach lets us transform our coded classes into database application, which means code first lets us to define our domain model using POCO (plain old CLR object) class rather than using an XML-based EDMX files which has no dependency with Entity Framework.

Which is better IQueryable or IEnumerable?

So if you working with only in-memory data collection IEnumerable is a good choice but if you want to query data collection which is connected with database `IQueryable is a better choice as it reduces network traffic and uses the power of SQL language.


1 Answers

Because you are querying an IEnumerable (ie: LINQ to Objects) not IQueryable (ie: LINQ to Entities) given by EF.

Instead you should use

IEnumerable<History> results = context.History.Where(h => h.Person.Id = "sfssd").OrderBy(h => h.OnDate).Take(50)
like image 137
Eranga Avatar answered Sep 27 '22 23:09

Eranga