2012-01-05 99 views
1

我正在使用實體框架和.Net 4 MVC 3.在我的控制器的創建方法中,我帶入一個員工對象,用於在我的數據庫中創建條目。實體框架 - 創建和使用導航屬性

public class Employee 
{ 
    public int Id { get; set; } 
    public int ManagerId { get; set; } 
    public virtual Employee Manager { get; set; } 
} 

public ActionResult Create(Employee model) 
{ 
    if (ModelState.IsValid) 
    { 
     db.Employees.Add(model); 
     db.SaveChanges(); 

     // Now I want to use the navigation properties 
     Notification(model.Manager.Name); 
    } 
} 

我從視圖發回管理員標識。現在,如果我重定向到詳細信息頁面,管理器已創建 - 但是當我嘗試訪問它時,如上所示,它爲空。我不得不訴諸的是:

if (ModelState.IsValid) 
{ 
    model.Manager = _employeeRepository.Get(model.ManagerId); 
    db.Employees.Add(model); 
    db.SaveChanges(); 

    // Now this works 
    Notification(model.Manager.Name); 
} 

但是,這似乎並不正確。 EF確實爲我創建了Manager對象,那麼爲什麼我需要手動獲取並設置它?難道我做錯了什麼?

回答

2

儘管看起來有些不對,但這是預期的功能,您的解決方案大致正確。 EF DbContext不會自動獲取Manager屬性,因爲這樣做可能會代價很高。如果它自動完成並且不想這麼做,那麼你會對EF生氣。答案(和你原來的解決方案)是在後續的調用中明確地獲取數據。

我建議稍微不同的實現:

if (ModelState.IsValid) 
{ 
    db.Employees.Add(model); 
    db.SaveChanges(); 

    // Get the manager name only after the SaveChanges is successful 
    // Will fail if the manager ID is not valid 
    var managerName = db.Managers.Where(mgr => mgr.ManagerId == model.ManagerId).Select(mgr => mgr.Name).Single(); 
    Notification(managerName); 
} 
+0

好了,現在是非常合情合理的,實際上似乎沒錯!謝謝。 – Terry 2012-01-05 20:29:26