Hei*_*tad 4 c# entity-framework-6
我遇到了EF6延迟加载的问题.我搜索过StackOverflow,但我发现的其他问题并不适合我的情况.
我正在使用virtual
关键字,我的课程是public
.LazyLoadingEnabled
并且ProxyCreationEnabled
都被设置为true
.
当我打开一个course
从数据库对象,presentationId
被设置为正确id
并且presentation
是null
这是正确的,因为它没有被加载.
当我将presentation
属性传递给PresentationsController.ToDto()
方法时,它应该是延迟加载的,但是我null reference
在方法中得到一个异常,因为它仍然存在null
.
我知道关系正在起作用,因为当我强制加载a的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; }
}
Run Code Online (Sandbox Code Playgroud)
我的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;
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
如果要通过动态代理使用延迟加载,则实体必须已显式声明公共构造函数.(如果你有其他参数)
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; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1249 次 |
最近记录: |