I have a class model like this:
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; }
}
I am trying to update only one entry using this code: (contexto is my 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);
}
For any reason i am getting this error:
System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Perfils' with unique index 'IX_Rol'. The duplicate key value is (3).
I understand that any entry added has to have a unique rol. The problem is that i am not trying to insert!!, i want to update the rol and description properties of the entry. I am testing this with only one entry in the table and i want to update it.
I have tested many things like change the state of the entry to modified or attach the entry. Some of this tests insert a new entry in db, giving me two entries in the table. I don't understand why the entry is not being updating. I think this trouble is caused because of the Unique column Rol.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…