[英]EF6 does not lazy load navigation property
我遇到了EF6延迟加载的问题。 我搜索过StackOverflow,但我发现的其他问题并不适合我的情况。
我正在使用virtual
关键字,我的课程是public
。 LazyLoadingEnabled
和ProxyCreationEnabled
均设置为true
。
当我从db加载一个course
对象时, presentationId
被设置为正确的id
而presentation
是null
,这是正确的,因为它还没有被加载。
当我将presentation
属性传递给PresentationsController.ToDto()
方法时,它应该是延迟加载的,但是我在方法中得到一个null reference
异常,因为它仍然是null
。
我知道关系正在起作用,因为当我在Watch window
强制加载course
的presentation
属性时,在public static CourseDto ToDto(Course item, DnbContext db)
方法中加载了一个断点。 看图像:
如您所见, item.presentation
为null
:
当我手动评估引用与item
对象相同的表示的db.courses.Find(257).presentation
,它们都被加载:
这是我的POCO:
public abstract class BaseModel : ISoftDelete {
public int id { get; set; }
}
public class Course : BaseModel {
[Required]
public int presentationId { get; set; }
public virtual Presentation presentation { get; set; }
}
我的Web API控制器方法:
// GET api/Courses/5
public CourseDto GetCourse(int id) {
var item = db.courses.FirstOrDefault(x => x.id == id);
return ToDto(item, db);
}
public static CourseDto ToDto(Course item, DnbContext db) {
var dto = new CourseDto();
if (item.presentationId > 0) dto.presentation = PresentationsController.ToDto(item.presentation, db);
return dto;
}
有任何想法吗?
如果要通过动态代理使用延迟加载,则实体必须已显式声明公共构造函数。 (如果你有其他参数)
public abstract class BaseModel : ISoftDelete {
public BaseModel() { }
public int id { get; set; }
}
public class Course : BaseModel {
public Course() { }
[Required]
public int presentationId { get; set; }
public virtual Presentation presentation { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.