Entity Framework: Navigation Properties Issue

前端 未结 4 1177
野的像风
野的像风 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 23:01

    One workaround for this is to flip your query around, though it means avoiding using navigation properties in general. (Actual implementation will vary with your model.)

    var allStudents =
       context
       .Students
       .Where(s => s.CourseID == course.ID) // depends on your model
       .Where(s => s.Active)
       .ToList();
    

    I prefer this to using the Entry method, since I use a general interface with my models and I don't want to expose EF6 types.

    Another way to avoid exposing EF6 types is to write a method like this:

    public IQueryable Nav(
       TParent pParent,
       Expression>> pNavigationExpression
    ) where TParent : class
    where TChild : class =>
       Entry(pParent)
       .Collection(pNavigationExpression)
       .Query();
    

    Used something like this:

    var allStudents =
       context
       .Nav(course, c => c.Students)
       .Where(s => s.Active)
       .ToList()
    

提交回复
热议问题