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

后端 未结 5 842
没有蜡笔的小新
没有蜡笔的小新 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().Attach(entity); //attach
    
            context.SaveChanges(); //save it
        }
        return true;
    }
    

提交回复
热议问题