Change primary Key in ASP.NET MVC5

0

Good morning, I read several posts and several pages that say that this is not recommended, in fact throws an error by bringing a record, change the password and save. I leave the code:

 List<Model> registroAUpdatear = (from s in db.Model where s.Id == IdAnterior select s).ToList();

        for (var i = 0; i < registroAUpdatear.Count; i++)
        {
            registroAUpdatear[i].Id = IdNuevo;
            db.Model.Add(registroAUpdatear[i]);
        }

This produces an exception:

  

"The property is part of the object's key information and can not be   modified. "

I understand that there is a way to do it, or rather 2 ways:

1-Create a stored procedure that makes the high and low from the DB and call it with entity framework.

2-Make a new Model (), passing the attributes of the model to modify, one by one and then add the new key.

The problem is that these 2 options take a long time for the number of models I have to modify. Can someone come up with another alternative? As much as possible he has gone through the same situation. Thanks!

    
asked by seojedaperez 14.07.2017 в 21:31
source

1 answer

0

I already found the solution: basically I would have to create 2 "List", one of "AUpdatear" and another one of "ABorrar" and load them before any action. Then resort to the For each of Baja, do SaveChanges, then the For each of Update, do SaveChanges and you're done. Just try it and it works.

List<NombreDelModel> modelAUpdatear = (from s in db.NombreDelModel where s.Id== IdViejo select s).ToList(); 
List<NombreDelModel> modelABorrar = (from s in db.NombreDelModel where s.Id== Id select s).ToList(); 
for (var i = 0; i < modelABorrar.Count; i++) 
  { 
    db.NombreDelModel.Remove(modelABorrar[i]);
  } 
db.SaveChanges(); 
for (var i = 0; i < modelAUpdatear .Count; i++) 
  {
    modelAUpdatear [i].Id = IdNuevo2; 
    db.NombreDelModel.Add(modelAUpdatear[i]); 
  }

Keep in mind that, if there is a relation by primarykey / foreignkey, first it is deleted from the last foreign key to the first primary key but it is updatea from the first primary key to the last foreign key , and obviously all List are loaded at the beginning, before any action. The truth is an interesting code, look in several places and nobody had thought of it.

    
answered by 14.07.2017 / 22:00
source