I have two tables in my database that contain the same columns. TBL one and TBL two which is history table. When I am entering data into TBL 1, I want to move all data from TBL 1 to Tbl 2 (as history data) using EF Core 2.2.
I don't want to write unnecessary loops to make the code ugly.
var MyEntity = new MyEntities();
var TBL1 = MyEntity.TBL1.Find();
var TBL2 = new TBL2();
TBL2.CurrentValues.SetValues(TBL1);
//CurrentValues is not accept in code. Giving me build error
MyEntity.TB2.Add(data2);
MyEntity.TB1.Remove(data1);
MyEntity.SaveChanges();
All I need is copy SQL data from table 1 to table 2 using EF and avoiding loops. Any example with mapper or anything which works will help.
Add a navigation property to your TBL2 model:
public TBL1 TBL1 { get; set; }
Add a projection to your TBL1 model like this:
public static Expression<Func<TBL1, TBL2>> Projection
{
return tbl1 => new TBL2
{
Prop1 = tbl1.Prop1,
Prop2 = tbl1.Prop2,
TBL1 = tbl1,
};
}
And use the projection to have instances of TBL1 and TBL2 like this:
var MyEntity = new MyEntities();
var tbl2 = MyEntity.TBL1.Where(x => x.Id == id).Select(TBL1.Projection).SingleOrDefault();
vat tbl1 = tbl2.TBL1;
MyEntity.TB2.Add(tbl2);
MyEntity.TB1.Remove(tbl1);
MyEntity.SaveChanges();