Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

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

I have a class model like this:

public class Perfil
        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.

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I finally discovered what was happend. I should have told in the question that this method were being executed from a unit test project. I was doing the execution in the following order:

  • Post
  • Get
  • Update
  • Delete

Besides, the whole operation was within a [TestMethod]. It seems that use the same object posted for putting makes the entity thinks that two objects are attached to it. That's why some of the tests give me as result two insertions. The solution was to split Post, Get, Update and Delete into a single [TestMethod] for each one.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share