3つのEntityFramework(4.3)オブジェクト、Member、Address、およびStateがあります。彼らはこのように見えます:
public class Member
{
public int Id { get; set; }
public virtual Address Address { get; set; }
/*other properties removed for brevity*/
}
public class Address
{
public int Id { get; set; }
public virtual State State { get; set; }
/*other properties removed for brevity*/
}
public class State
{
public int Id { get; set; }
public string Name { get; set; }
public string Abbreviation { get; set; }
public virtual ICollection<Address> Address { get; set; }
}
アドレスの関係を更新すると、すべてが正常に機能します。以下のコードを参照してください。
[HttpPost]
public ActionResult Update(MemberUpdateModel model)
{
if (!ModelState.IsValid)
{
model.SetStateSelectList(_db, model.SelectedStateId);
return View(model);
}
_db.Entry(model.Member).State = EntityState.Modified;
_db.Entry(model.Member.Address).State = EntityState.Modified;
_db.SaveChanges(); // works
return RedirectToAction("Index");
}
次に、次のようにアドレスと状態の関係の更新を追加します。
[HttpPost]
public ActionResult Update(MemberUpdateModel model)
{
if (!ModelState.IsValid)
{
model.SetStateSelectList(_db, model.SelectedStateId);
return View(model);
}
_db.Entry(model.Member).State = EntityState.Modified;
_db.Entry(model.Member.Address).State = EntityState.Modified;
// added for address/state relationship
var selectedState = _db.States.FirstOrDefault(q => q.Id == model.SelectedStateId);
model.Member.Address.State = selectedState;
_db.SaveChanges();
return RedirectToAction("Index");
}
上記のコードを実行すると、次のエラーが発生します。
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
この動作を引き起こすために私は何を間違っていますか?