如何使用 Entity Framework 更新具有唯一列的 table 上的条目 6

How to update an entry on table with unique column using Entity Framework 6

我有一个这样的 class 模型:

public class Perfil
{
        [Key]
        public int ID { get; set; }
        public DateTime FechaCreacion { get; set; }
        [Index(IsUnique = true)]
        public Modelo.Enumeraciones.ERoles Rol { get; set; }
        public string Descripcion { get; set; }
}

我正在尝试使用此代码仅更新一个条目:(contexto 是我的 dbContext)

public async Task<IHttpActionResult> Put(int id, [FromBody]Models.Usuarios.Perfil value)
{
            if (id != value.ID) {
                return InternalServerError(new Exception("id de URL: "+id+ " no coincide con el del objeto enviado en el cuerpo: " + value.ID));
            }

            Models.Usuarios.Perfil perfil = contexto.Perfiles.SingleOrDefault(a => a.ID == id);

            if (EqualityComparer<Models.Usuarios.Perfil>.Default.Equals(perfil, default(Models.Usuarios.Perfil)))
            {
                return InternalServerError(new Exception("No existe un registro con id " + id + " en la tabla de perfiles."));
            }

            perfil.Descripcion = value.Descripcion;
            perfil.Rol = value.Rol;

            await contexto.SaveChangesAsync();

            return Ok(id);
}

出于任何原因我收到此错误:

System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Perfils' with unique index 'IX_Rol'. The duplicate key value is (3).

我了解添加的任何条目都必须具有唯一角色。问题是我不是要插入!!,我想更新条目的 rol 和描述属性。我正在 table 中仅使用一个条目进行测试,我想更新它。

我测试了很多东西,比如将条目的状态更改为已修改或附加条目。其中一些测试在 db 中插入一个新条目,在 table 中给了我两个条目。我不明白为什么条目没有更新。我认为这个麻烦是因为 Unique 列 Rol.

我终于知道发生了什么事了。我应该在问题中告诉这个方法是从单元测试项目中执行的。我按照以下顺序执行:

  • Post
  • 得到
  • 更新
  • 删除

此外,整个操作都在一个[TestMethod]中进行。似乎使用发布的相同对象进行放置会使实体认为有两个对象附​​加到它。这就是为什么一些测试给我两次插入的结果。解决方案是将 Post、Get、Update 和 Delete 拆分为一个单独的 [TestMethod]。