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'.
Before This issue i faced another issue of ObjectStateManger Extension not found error in the code :
entities.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
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);
}
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);
}
In the answer you have referenced, the answer has this:
var manager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager;
^^
||
see this is db
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();
You are trying to do this:
var manager = ((IObjectContextAdapter)entity).ObjectContext.ObjectStateManager;
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.