无法将类型 'DBContext.Models.Contact' 的对象转换为类型 'System.Data.Entity.Infrastructure.IObjectContextAdapter'

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

我正在尝试实施 "Repository-Pattern" 并且 Contact-Controller 中的 "Edit" 方法正在使用 Contact-Repository 中的 "Attach Method" 抛出错误。

Additional information: Unable to cast object of type 'Contacts.Models.Contact' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'.

在这个问题之前我遇到了另一个问题 ObjectStateManger Extension not found 代码中的错误:

entities.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);

所以我不得不使用新变量 "manager" 作为另一个堆栈溢出线程问题的解决方案 () 联系人存储库中的附加方法

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 的 Contact Controller 中的编辑方法

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);
            }

在您引用的中,答案是这样的:

var manager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager;
                                      ^^
                                      ||
                                   see this is db

之所以可行,是因为该问题中的 OP 具​​有实现 IObjectContextAdapter 的类型。该问题中的 OP 是这样的:

SampleContext db = new SampleContext();

您正在尝试这样做:

var manager = ((IObjectContextAdapter)entity).ObjectContext.ObjectStateManager;

您的 entity 未实现该接口,因此您无法将其转换为 IObjectContextAdapter,这正是错误消息告诉您的内容。