简体   繁体   中英

Entity FrameWork MVC ViewModel

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.

The following code works assuming that there is a relationship between first and second model. You don't need to save changes twice.

[HttpPost]
public class ActionResult Save(MyViewModel vmData)
{
    FirstModel firstModel = new FirstModel();
    SecondModel secondModel = new SecondModel();

    firstModel.MyDetails = vmData.MyDetails;
    secondModel.MyDetails = vmData.MyDetails2;

    secondModel.FirstModel = firstModel;
    db.SecondModel.Add(secondModel);
    db.SaveChanges();
}

It will execute two queries in two queries in one transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM