私は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は私のためにマネージャオブジェクトを作成します。なぜ手動で取得して設定する必要がありますか?私は何か間違っているのですか?
[OK]を!ありがとう。 – Terry