Everton Lenger
Everton Lenger

Reputation: 1446

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?

Upvotes: 4

Views: 16283

Answers (2)

Bassam Alugili
Bassam Alugili

Reputation: 17043

You can also use SQL to transfer the data between the tables in SQL Server. This is a very fast way but it is not very clean for a clean coder.

You can create an interface e.g. IExecuteSQLQuery with method Excute(DbContext) and a class TransferDataFromT1ToT2:IEexcuteSQLQuery in this way you will get a generic way to handle the sql text.

dbContext.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, 
"INSERT INTO T2 (CustomerName, Country) 
SELECT SupplierName, Country FROM T1 
WHERE Country ='Germany';" );

Upvotes: 4

Claies
Claies

Reputation: 22323

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.

Upvotes: 10

Related Questions