问题
I am using entity framework. I have a table with auto generated primary key and lot of foriegn key relationship with other master data tables. We need a copy functionality, wherein we can select any existing row from the table and insert that as a copy in the same table.
I need to copy all the fields, but it should be a different record, and need the procedure/LINQ for same.
Please suggest, how should I proceed.
回答1:
You can do this:
context.Entry(oCustomer).State = EntityState.Added;
this will cause EF to think this entity is a new one and after you call SaveChanges
it will be inserted in the database and not updated.
If you have an object graph - you need to traverse it and make sure all child entities are set to EntityState.Unchanged
or they will be duplicated after SaveChanges
.
来源:https://stackoverflow.com/questions/20322778/insert-a-copy-of-existing-row-using-linq-to-entities