2012-01-05 14 views
1

私はEntity Frameworkと.Net 4 MVCを使用しています。私のコントローラのcreateメソッドでは、自分のデータベースにエントリを作成するために使用する従業員オブジェクトを取ります。Entity Framework - ナビゲーションプロパティの作成と使用

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

私はビューからマネージャIDを返信します。今、詳細ページにリダイレクトすると、マネージャーが作成されました。しかし、私が上記のようにアクセスしようとすると、nullになります。私が頼らなければならなかったのは、

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

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

ですが、これは正しいようです。確かにEFは私のためにマネージャオブジェクトを作成します。なぜ手動で取得して設定する必要がありますか?私は何か間違っているのですか?

答えて

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

[OK]を!ありがとう。 – Terry

関連する問題