0
我想實現「存儲庫模式」,並在接觸控制器「編輯」的方法是使在接觸庫使用「連接方法」拋出錯誤。無法投型「DBContext.Models.Contact」的對象鍵入「System.Data.Entity.Infrastructure.IObjectContextAdapter」
Additional information: Unable to cast object of type 'Contacts.Models.Contact' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'.
之前這個問題,我面對ObjectStateManger擴展的另一個問題沒有發現錯誤代碼:
entities.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
,所以我不得不使用新的變量「經理人」從另一個棧的問題的解決方案在流線(ObjectStateManager no definition issue) 附加方法在非接觸式存儲庫
public void Attach(Contact entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
var manager = ((IObjectContextAdapter)entity).ObjectContext.ObjectStateManager;
entities.Contacts.Attach(entity);
manager.ChangeObjectState(entity, EntityState.Modified);
}
編輯方法聯繫控制器,使得使用C++ ontactRespository
public ActionResult Edit(int?id)
{
Contact contact = repo.Get(c => c.ID == id);
if (contact == null)
{
return HttpNotFound();
}
return View(contact);
}
//
// POST: /Contacts/Edit/5
[HttpPost]
public ActionResult Edit(Contact contact)
{
if (ModelState.IsValid)
{
repo.Attach(contact);
repo.SaveChanges();
return RedirectToAction("Index");
}
return View(contact);
}
我更換了整個代碼附加與該行和其工作。 'entities.Entry(實體).STATE = EntityState.Modified;' 即使在我的代碼,我 '私人CTEntities實體=新CTEntities();' 而我更換 'VAR經理=((IObjectContextAdapter)實體).ObjectContext.ObjectStateManager;' 我取代實體這是我的DbContext及其工作正常的情況下「實體」。非常感謝你! – Arun3x3