Entity Framework Find method not working properly

最后都变了- 提交于 2019-12-01 06:16:50

Find works correctly because EF never loads related entities itself. To load related properties you must either use eager or lazy loading. The third option is sometimes refered as explicit loading.

Lazy loading will provide you automatic loading of related entities but it will generate additional queries to the database. Related entity or related collection will be loaded when you access the property for the first time. To use lazy loading you must mark all navigation properties in the entity as virtual (@ckal provided you an example). Also lazy loading works only if context used to load the main entity is still alive.

Eager loading will define which relation must be load together with your main entity. Eager loading is executed by Include method. You can rewrite Find as:

Course c = _unitOfWork.DbContext
                      .Set<Course>()
                      .Include(c => c.Students)
                      .Include(c => c.Teacher)
                      .SingleOrDefault(c => c.CourseId == keyValue);

Explicit loading will allow you to explicitly say that some relation should be loaded. You can even define some condition for loading related entities which is not possible with other two methods. You must first load the main entity and before disposing the context you can do something like:

context.Entry(course).Collection(c => c.Students).Load();

Add virtual to your navigation properties to enable lazy loading.

public class Course
{
    [Key, DatabaseGenerated(DatabaseGenerationOption.Identity)]
    public Guid CourseId { set; get; }
    public virtual ICollection<Student> Students { set; get; }
    public virtual Teacher Teacher { get; set; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!