【问题标题】:EF6 does not lazy load navigation propertyEF6 不延迟加载导航属性
【发布时间】:2014-03-05 09:56:55
【问题描述】:

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

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

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

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

我知道这些关系是有效的,因为当我在 Watch window 中强制加载 coursepresentation 属性并在 public static CourseDto ToDto(Course item, DnbContext db) 方法处设置断点时,它会被加载。查看图片:

如您所见,item.presentationnull

当我手动评估 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;
}

有什么想法吗?

【问题讨论】:

    标签: c# entity-framework-6


    【解决方案1】:

    如果你想通过动态代理使用延迟加载,实体必须明确声明公共构造函数。 (如果你有其他带参数的)

    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; }
    }
    

    【讨论】:

    • 上帝保佑你!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    相关资源
    最近更新 更多