Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "transfer" the data from one table to another with EF?

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?

like image 406
Everton Lenger Avatar asked Dec 14 '22 05:12

Everton Lenger


1 Answers

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.

like image 168
Claies Avatar answered Mar 16 '23 12:03

Claies