I have some code like belows. This works but I think it’s not clear enough and requires me to write lengthy code (assigning each property manually).
// POST: /TableA/Edit
[HttpPost]
public ActionResult Edit(TableA formdata)
{
TableA temp = myDB.TableA.First(a=>a.Id == formdata.Id);
//A foreign key model in another TableB
var tbb = myDB.TableB.First(a => a.Id == formdata.TableB.Id);
temp.TableB = tbb;
//fields in this table
temp.field1= formdata.field1;
temp.field2= formdata.field2;
temp.field3= formdata.field3;
myDB.SaveChanges();
return RedirectToAction("Index");
}
Can I have some code similar to object initializers:
TableA temp = myDB.TableA.First(a=>a.Id == formdata.Id)
{
TableB = myDB.TableB.First(a => a.Id == formdata.TableB.Id),
field1= formdata.field1,
field2= formdata.field2,
field3= formdata.field3,
}
myDB.SaveChanges();
return RedirectToAction("Index");
Using i.e. AutoMapper you could write it like this (possibly have to set up to limit the mapping between the objects to the properties you want copied):