0

How can I create a copy an existent entity(dbset) but changing the primary key?

For example, I have the code below:

foreach(var item in db.PedidoMassPro_Detail.Where(o => o.Order_Number.Equals(orderNumber)))
{
    PedidoMassPro_Detail newItem = item;
    newItem.Order_Number = "TESTE111";
    db.PedidoMassPro_Detail.Add(newItem);
    db.SaveChanges();
}

I get the error: New transaction is not allowed because there are other threads running in the session.

There is a lot of columns, so that is the reason why I not setting each column, I will need a copy and the only thing that I need to change is the Primary Key (Order_Number).

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Jairo Franchi
  • 367
  • 1
  • 2
  • 13
  • 1
    you can always create a copy of the object with Reflection then add the copy to db, check out https://stackoverflow.com/questions/6569486/creating-a-copy-of-an-object-in-c-sharp – hazimdikenli Mar 26 '18 at 14:29

1 Answers1

1

get a list of untracked objects from EF by specifying that you want them AsNoTracking, if it is tracked, EF will know that entity exists in the db already, and instead of adding it as new entity, it will try to update.

 db.PedidoMassPro_Detail.Where(o => o.Order_Number.Equals(orderNumber).AsNoTracking()

use toList to materialize objects, I think this is the reason you are getting the current error, while iterating a list, you are trying to change the list, so make sure first you get a list of items matching the criteria.

var orderSet = db.PedidoMassPro_Detail.Where(o => o.Order_Number.Equals(orderNumber).AsNoTracking().ToList();

use single save to serialize changes to db

foreach(var item in orderSet )
{
    item.Order_Number = "TESTE111";
    //handle primary key, is it Guid, auto identity? 
    db.PedidoMassPro_Detail.Add(item);
}
db.SaveChanges();
hazimdikenli
  • 5,709
  • 8
  • 37
  • 67