EF6不会延迟加载导航属性

时间:2014-03-05 09:56:56

标签: c# entity-framework-6

我遇到了EF6延迟加载的问题。我搜索过StackOverflow,但我发现的其他问题并不适合我的情况。

我正在使用virtual关键字,我的课程为publicLazyLoadingEnabledProxyCreationEnabled都设置为true

当我从数据库加载course对象时,presentationId设置为正确的idpresentationnull这是正确的,因为它尚未加载。

当我将presentation属性传递给PresentationsController.ToDto()方法时,它应该是延迟加载的,但我在方法中得到null reference异常,因为它仍然是null。< / p>

我知道这些关系正在发挥作用,因为当我强制加载presentationcourse的{​​{1}}属性时,Watch window方法的断点为public static CourseDto ToDto(Course item, DnbContext db)加载。见图:

您可以看到item.presentationnull

enter image description here

当我手动评估引用与db.courses.Find(257).presentation对象相同的演示文稿的item时,它们都被加载:

enter image description here

以下是我的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;
}

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

如果要通过动态代理使用延迟加载,则实体必须已显式声明公共构造函数。 (如果你有其他参数)

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; }
}
相关问题