EF6延迟加载出现问题。我已经搜索了StackOverflow,但是发现的其他问题与我的情况不符。
我使用的virtual
关键字是我的课程public
。LazyLoadingEnabled
并且ProxyCreationEnabled
都设置为true
。
当我打开一个course
从数据库对象,presentationId
被设置为正确id
并且presentation
是null
这是正确的,因为它没有被加载。
当我将presentation
属性传递给PresentationsController.ToDto()
方法时,应该将其延迟加载,但是null reference
在方法内部却出现了异常,因为它仍然是null
。
我知道,关系工作,因为当我强迫加载presentation
的特性course
在Watch window
同在一个破发点public static CourseDto ToDto(Course item, DnbContext db)
就被加载方法。查看图片:
正如你看到的item.presentation
是null
:
当我手动评估db.courses.Find(257).presentation
哪个对象引用了相同的表示形式时item
,它们都被加载:
这是我的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; }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句