I have two tables in my database that contains the same columns. I have a record in one table (named TB1) and I want to "transfer" it to the another one (named TB2) using EF.
I'm not very familiar with EF, so my thoughts were in this direction:
var testEntity = new TestEntities();
var data1 = testEntity.TB1.Find(id);
var data2 = new TB2();
// Pass all the properties from one object (data1) to another (data2)
testEntity.TB2.Add(data2);
testEntity.TB1.Remove(data1);
testEntity.SaveChanges();
But, to continue with this logic, I have to pass all the properties from one object to another, manually. And it contains a lot of properties (about 50).
As they have the same properties, I really think there must be an easier way to execute this process, but I don't know how.
Is there an easier way to "transfer" this data?
Entity Framework has functions to handle copying object properties. See https://msdn.microsoft.com/en-us/data/jj592677.aspx.
The easiest way to do this would be to use CurrentValues.SetValues()
.
var testEntity = new TestEntities();
var data1 = testEntity.TB1.Find(id);
var data2 = new TB2();
data2.CurrentValues.SetValues(data1);
testEntity.TB2.Add(data2);
testEntity.TB1.Remove(data1);
testEntity.SaveChanges();
This technique is sometimes used when updating an entity with values obtained from a service call or a client in an n-tier application. Note that the object used does not have to be of the same type as the entity so long as it has properties whose names match those of the entity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With