Search code examples
c#.netentity-frameworklinqlinq-to-entities

Entity framework. Insert values from one entity class to another different one


Here is my problem...

I've got one entity class, and I want to keep historical values from this table. Every time each record is changed, I want to insert a snapshot from this record into another table (with the same fields). I could do this field by field, but I'm sure there should be a simple way of doing this.

I've tried something like this, but it doesn't work:

var t1 = context.TABLE1.Find(id);
var t2 = new TABLE2();
context.Entry(t2).CurrentValues.SetValues(t1);
context.SaveChanges();

I've found this How to "transfer" the data from one table to another with EF? but it doesn't work for me, because my tables can't do what is said on this post

t2.CurrentValues.SetValues(t1);

Any ideas?


Solution

  • You could use a package like AutoMapper to create a mapping between the Table1 and Table2 classes. They have good documentation on how to get that set up. You could also override the SaveChange() method to handle the creation/saving of the historical record.