2014-03-05 38 views
4

我遇到了EF6延遲加載的問題。我搜索了StackOverflow,但我發現的其他問題不適合我的情況。EF6不會延遲加載導航屬性

我使用的是virtual關鍵字,我的課程是publicLazyLoadingEnabledProxyCreationEnabled都設置爲true

當我從分貝加載course對象,presentationId被設置爲正確的idpresentationnull這是正確的,因爲它尚未裝載。

當我通過presentation屬性爲PresentationsController.ToDto()方法應該是懶加載,但我得到的方法內null reference例外,因爲它仍然null

我知道,關係工作,因爲當我強迫與它被加載的public static CourseDto ToDto(Course item, DnbContext db)方法一個破發點加載courseWatch windowpresentation財產。見圖片:

正如你可以看到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; 
} 

任何想法?

回答

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

上帝保佑你!謝謝! –