实体框架:更新实体 - ObjectStateManager中已存在具有相同密钥的对象

时间:2013-01-25 10:54:31

标签: c# entity-framework entity-framework-5

我正在使用通用存储库。我描述了我的所作所为:
我从DB获得实体 2.从该实体创建视图模型(使用automapper)
3.然后在对视图模型进行一些修改后,我将视图模型转换为 User enity。
4.调用以下代码:

public void UpdateUser(User user)
{
   _repository.Update(user);
   _repository.SaveChanges();
}  

但是,我得到错误:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

我知道为什么会显示此错误(旧实体已附加)。我看到其他问题,有不同的解决方案,我无法理解,不能重写我的代码。我是Entity Framework的新手。请帮我改写我的存储库。

感谢。
这是我的存储库类:

public class EfRepository : IRepository
    {
        #region Private fields

        private PcpContext _context;

        #endregion


        #region Constructors

        public EfRepository(PcpContext context)
        {
            _context = context;

        }

        #endregion


        #region Implementation of IRepository

        public IQueryable<T> Query<T>() where T : class
        {
            return _context.Set<T>();
        }

        public void Save<T>(T entity) where T : class
        {
            _context.Set<T>().Add(entity);
        }

        public void Update<T>(T entity) where T : class
        {
            _context.Set<T>().Attach(entity);
            _context.Entry<T>(entity).State = EntityState.Modified;
        }

        public void Delete<T>(T entity) where T : class
        {
            _context.Set<T>().Attach(entity);
            _context.Entry<T>(entity).State = EntityState.Deleted;
        }

        public void DeleteById<T>(int entityId) where T : class
        {
            var entity = _context.Set<T>().Find(entityId);
            _context.Entry<T>(entity).State = EntityState.Deleted;
        }

        public void SaveChanges()
        {
            _context.SaveChanges();
        }

        public IGenericTransaction BeginTransaction()
        {
            return new EfTransaction(this);
        }

        public void EndTransaction(IGenericTransaction transaction)
        {
            if (transaction != null)
            {
                transaction.Dispose();
                transaction = null;
            }
        }

        public void Dispose()
        {
            if (this._context != null)
            {
                this._context.SaveChanges();
                (this._context as IDisposable).Dispose();
                this._context = null;
            }
        }

        #endregion

堆栈跟踪:

at System.Data.Objects.ObjectContext.VerifyRootForAdd(Boolean doAttach, String entitySetName, IEntityWrapper wrappedEntity, EntityEntry existingEntry, EntitySet& entitySet, Boolean& isNoOperation)
   at System.Data.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
   at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClass2.<Attach>b__1()
   at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Attach(Object entity)
   at System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value)
   at System.Data.Entity.Infrastructure.DbEntityEntry`1.set_State(EntityState value)
   at DT.PCP.DataAccess.Impl.EfRepository.Update[T](T entity) in c:\Users\Max\Documents\Visual Studio 2012\Projects\DT.PCP\Sources\DT.PCP\DT.PCP.DataAccess.Impl\EfRepository.cs:line 51
   at DT.PCP.BussinesServices.Impl.UserService.UpdateUser(User user) in c:\Users\Max\Documents\Visual Studio 2012\Projects\DT.PCP\Sources\DT.PCP\DT.PCP.BussinesServices.Impl\UserService.cs:line 89
   at DT.PCP.Web.Portal.Controllers.CabinetController.Edit(UserInfoViewModel userInfo) in c:\Users\Max\Documents\Visual Studio 2012\Projects\DT.PCP\Sources\DT.PCP\DT.PCP.Web.Portal\Controllers\CabinetController.cs:line 51
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.<>c__DisplayClass1.<WrapVoidAction>b__0(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()

0 个答案:

没有答案