我试图在Contact中实现"Repository-Pattern“和"Edit”方法-Controller正在使用Contact中的“附加方法”--Repository正在抛出错误。
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);因此,我不得不使用新的变量"manager“来解决另一个堆栈流线程(ObjectStateManager no definition issue)连接方法在Contact-Repository中的问题。
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);
}利用ContactRespository的接触式控制器的编辑方法
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);
}发布于 2017-02-16 19:38:32
在您引用的answer中,答案如下:
var manager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager;
^^
||
see this is db这是因为问题中的OP有一个实现IObjectContextAdapter的类型。该问题的执行部分如下:
SampleContext db = new SampleContext();你想这么做:
var manager = ((IObjectContextAdapter)entity).ObjectContext.ObjectStateManager;您的entity没有实现该接口,因此不能将其转换为IObjectContextAdapter,而这正是错误消息告诉您的。
https://stackoverflow.com/questions/42282986
复制相似问题