0
我知道這個主題有很多問題,但我似乎找不到與我的場景有關的任何問題。DBContext在控制器中生成,仍然得到兩個對象之間的關係...不同的ObjectContext對象
即時得到「兩個對象之間的關係不能被定義,因爲它們連接到不同的ObjectContext對象」上Inventory CurrentInventory = db.Inventories.Find(injection.InventoryID);
這工作很我第一次運行它,並隨後嘗試都失敗。
我不明白我是如何獲得不同的上下文對象。
我的控制器:
public class InventoriesController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Inventories/Edit
public ActionResult Edit()
{
return View(db.Inventories.ToList());
}
// POST: Inventories/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(List<Inventory> inventory)
{
//List<Inventory> inventory
if (inventory == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
foreach (Inventory injection in inventory)
{
Inventory CurrentInventory = db.Inventories.Find(injection.InventoryID);
CurrentInventory.Date = DateTime.Now;
CurrentInventory.Quantity = injection.Quantity;
CurrentInventory.LastChangedBy = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
}
if (ModelState.IsValid)
{
// db.Entry(inventory).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(EntityState.Modified);
}
}
編輯:
我回到了一個較爲單一更新方法,只是爲了看看是否會有幫助。我仍然得到相同的錯誤。所以我將其與其他控制器之一進行了比較,修改了Edit方法,並注意到我沒有使用.Find()方法,而是反覆對它們記錄自己並返回所需的對象。做這件事時,問題解決了。
// GET: Inventories/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Inventory inventory = db.Inventories.Find(id);
ViewData["Id"] = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
if (inventory == null)
{
return HttpNotFound();
}
return View(inventory);
}
// POST: Inventories/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "InventoryID,Quantity,LastChanged,Date")] Inventory inventory)
{
Inventory oldInventory = null;
foreach (var a in db.Inventories)
{
if (a.InventoryID == inventory.InventoryID)
{
oldInventory = a;
}
}
if (oldInventory == null)
{
return HttpNotFound();
}
if (ModelState.IsValid)
{
//db.Entry(inventory).State = EntityState.Modified;
TryUpdateModel(oldInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(inventory);
}
後續問題:
是否.Find()方法在實施創建另一個的DbContext使返回的對象本身是從完全不同的環境?
你應該做庫存CurrentInventorydb.Inventories.Find(x => x.InventoryID == injection.InventoryID); –