Entity Framework Code First IQueryable

后端 未结 2 1056
甜味超标
甜味超标 2021-01-12 05:23

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          


        
相关标签:
2条回答
  • 2021-01-12 06:00

    This question and the accepted answer are both a bit old. Code like this would, as the original question points, load the entire history for the person from the database - not good!

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

    With EF 6 there is an easy solution. Without rearranging your query, you can have it work the IQueryable way by making use of the DbContext.Entry method, the DbEntryEntity.Collection method, and the DbCollectionEntry.Query method.

    var results = dbContext
        .Entry(person)
        .Collection(p => p.History)
        .Query()
        .OrderBy(h => h.OnDate)
        .Take(50)
        .ToArray();
    
    0 讨论(0)
  • 2021-01-12 06:06

    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)
    
    0 讨论(0)
提交回复
热议问题