我可以限制使用LINQ和Entity Framework 5添加.include的级别吗?

我可以限制使用LINQ和Entity Framework 5添加.include的级别吗?,linq,entity-framework,c#-4.0,linq-to-entities,entity-framework-5,Linq,Entity Framework,C# 4.0,Linq To Entities,Entity Framework 5,鉴于以下情况: public class Department { public int DepartmentID { get; set; } public string Name { get; set; } public virtual ICollection<Course> Courses { get; set; } } public class Course { public int CourseID { get; set; } pub

鉴于以下情况:

public class Department
{
    public int DepartmentID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course
{
    public int CourseID { get; set; }
    public string Title { get; set; }
    public int Credits { get; set; }
    public int DepartmentID { get; set; }
    public virtual Department Department { get; set; }
}
        var departments = _DepartmentRepository.GetAll()
            .Include(c => c.courses);
然后我得到答案,里面有一个部门对象


是否有一种方法可以只包含课程而不返回部门对象。例如,我可以只包含一个级别(课程)。

您只包含一个级别。课程中的department对象就在那里,因为EF已经完成了一些关系修复,以便您可以从课程导航到该部门


如果你不想要系,那就直接上这些课程吧。即
context.Courses.ToList()或通过课程回购(如果有)。

获取实体时,EF将自动填充其已跟踪目标对象的导航属性。这意味着如果你说:

// Load the department with a PK of 1
_DepartmentRepository.Find(1);
然后,使用相同的上下文,例如:

// Load a course with PK of 17
_CourseRepository.Find(17);

如果此课程部门id为1,则EF将自动填充其部门导航属性,即使您未指定包含。您可以通过不将部门导航属性设置为虚拟来停止这种行为。

您是否找到了实现这一点的最佳方法?我也在为同样的问题挣扎。