无法将类型为"DBContext.Models.Contact"的对象转换为类型为"System.Data.Entity.Infrastructure.IObjectContextAdapter"的对象 [英] Unable to cast object of type 'DBContext.Models.Contact' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'
问题描述
我正在尝试实现Contact-Controller中的"Repository-Pattern",而"Edit"方法正在使用Contact-Repository中的"Attach Method"会引发错误.
I am trying to implement "Repository-Pattern" and "Edit" method in Contact-Controller is making use of "Attach Method" in Contact-Repository is throwing Error.
Additional information: Unable to cast object of type 'Contacts.Models.Contact' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'.
在此问题之前,我遇到另一个在代码中找不到ObjectStateManger扩展错误的问题:
Before This issue i faced another issue of ObjectStateManger Extension not found error in the code :
entities.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
因此,我不得不使用新的变量"manager"作为来自另一个线程流堆栈的问题的解决方案(
So i had to use new variable "manager" as a solution for the issue from another stack over flow thread (ObjectStateManager no definition issue) Attach Method in 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);
}
使用ControllerRespository的Contact Controller中的
Edit方法
Edit Method in Contact Controller that makes use of 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);
}
推荐答案
在之所以可行,是因为该问题中的OP具有实现IObjectContextAdapter
的类型.该问题中的OP具有以下内容:
That works because the OP in that question has a type which implements the IObjectContextAdapter
. The OP in that question has this:
SampleContext db = new SampleContext();
您正在尝试这样做:
var manager = ((IObjectContextAdapter)entity).ObjectContext.ObjectStateManager;
您的entity
没有实现该接口,因此您不能将其强制转换为IObjectContextAdapter
,而这正是错误消息告诉您的内容.
Your entity
does not implement that interface so you cannot cast it to IObjectContextAdapter
and that is exactly what the error message is telling you.
这篇关于无法将类型为"DBContext.Models.Contact"的对象转换为类型为"System.Data.Entity.Infrastructure.IObjectContextAdapter"的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!