Attaching an entity of type 'X' failed because another entity of the same type already has the same primary key value

后端 未结 5 807
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 09:25

ErrorMessage :

Attaching an entity of type \'FaridCRMData.Models.Customer\' failed because another entity of the same type already has the same prim

相关标签:
5条回答
  • 2021-01-04 09:55

    have you tried to mark your entity as modified BEFORE attach it to the context?

    like this:

    public bool Update(TEntity entity)
    {
        var entry = context.Entry(entity);
        if (entry.State == EntityState.Detached || entry.State == EntityState.Modified)
        {
            entry.State = EntityState.Modified; //do it here
    
            context.Set<TEntity>().Attach(entity); //attach
    
            context.SaveChanges(); //save it
        }
        return true;
    }
    
    0 讨论(0)
  • 2021-01-04 09:58

    I believe you might have invoked Select before the update, By default, DBContext will cache the record when they are fethced (Selected), use "AsNoTracking()" in your select call while fetching record.

    0 讨论(0)
  • 2021-01-04 10:05

    Try simple change state for entity wich you trying update and SaveChanges()

    public bool Update(TEntity entity)
    {
    
            context.Entry(entity).State = System.Data.EntityState.Modified;
            context.SaveChanges();
            return true;
    }
    
    0 讨论(0)
  • 2021-01-04 10:06

    If you are selecting some data in between Update operation (as i was getting problem). Don't use .ToList() or .Find() .... Instead of that use as IQueryable , then use .AsNoTracking()..... Problem solved.

    0 讨论(0)
  • 2021-01-04 10:06

    You need to detach the local version first and then do the update process

    var localEntity = dbContext.Set<theModel>()
        .Local
        .FirstOrDefault(f => f.Id == theModel.Id);
    if (localEntity != null)
    {
        dbContext.Entry(localEntity).State = EntityState.Detached;
    }
    dbContext.Entry(appModel).State = EntityState.Modified;
    
    0 讨论(0)
提交回复
热议问题