Unable to cast object of type 'DBContext.Models.Contact' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'

asp.net-mvc-5 c# entity-framework-6 repository-pattern

Question

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);
            }
1
0
5/23/2017 11:53:26 AM

Accepted Answer

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.

2
5/23/2017 11:53:26 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow