My question is simple, and wondering how this should be done properly.
Let's say I have 2 Models.
public class FirstModel
{
public int FirstModel {get; set;}
public string MyDetails {get; set;}
}
public class SecondModel
{
public int SecondModel {get; set;}
public int FirstModelID {get; set;}
public string MyDetails {get; set;}
public virtual <FirstModel> FirstModel {get; set;}
}
public class MyViewModel
{
public string MyDetails {get; set;}
public string MyDetails2 {get; set;}
//Or Foreign key to other models. You get the idea.
}
In my Controller. I instantiated my ViewModel and pass it to the View.
Now I am worried about my workflow and I believe that there is a best way to Insert or even Update Data for the Enitity Model.
My work flow is Make an Instance of the 2 Model and either Add it to the dbContext. Which is fine for me.
But the troublesome is the Updating part.
[HttpPost]
public class ActionResult Save(MyViewModel vmData)
{
FirstModel firstModel = new FirstModel();
SecondModel secondModel = new SecondModel();
firstModel.MyDetails = vmData.MyDetails;
secondModel.MyDetails = vmData.MyDetails2;
db.FirstModel.Add(firstModel);
db.SaveChanges();
secondModel.FirstModelID = firstModel.MyDetails;
db.SecondModel.Add(secondModel);
db.SaveChanges();
}
Now it seems simple in my part because there is only 1 property in FirstModel and 2 Properties to fill in SecondModel. But as the model goes, it is hard to manually fill them. Is there some technique like bind that can help me out with this? Any strategy for making it also available for Updating a dbContext?
while this Answer is helpful. enter link description here
This applies for the Model itself, wondering if I can use the same strategy for ViewModels. Thanks for checking my question.