Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
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
{
        [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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...