Entity Framework: Navigation Properties Issue

前端 未结 4 1123
野的像风
野的像风 2020-12-09 22:05

I am working with Entity Framework code-first, and I have a class Course which has a navigation property Students:

public virtual C         


        
4条回答
  •  时光说笑
    2020-12-09 22:44

    Lazy loading loads the entire set into memory. If you don't want that, switch lazy loading off by removing the virtual keyword and use the Query object on the DbEntry:

    public GetCourseWithActiveStudentsLoaded(int courseid)
    {
       var course= context.Courses.Find(courseid); 
    
       context.Entry(course)
              .Collection(c => c.Students)
              .Query()
              .Where(s => s.Active)
              .Load();
    
       return user
    }
    

    Is the "Active" flag an indicator that you are trying to implement soft delete? If so there is a solution here: Soft Delete in Entity Framework

    You can vote for filtered includes here: Allow filtering for Include extension method

    Another way to do it would be with inheritance. You could have an ActiveStudent inheriting from Student and an ActiveStudents navigation property as well as an AllStudents navigation property in the Course class

    public virtual Collection AllStudents { get; set;}
    public virtual Collection ActiveStudents { get; set;}
    

    Reference:

    Applying filters when explicitly loading related entities:

提交回复
热议问题