简体   繁体   中英

Saving data into multiple tables from the controller

I've got a ViewModel that includes multiple models:

public class MyViewModel
{
  Music.Models.Organizations Organizations {get; set;}
  Music.Models.People People {get; set;}
}

When the appropriate fields are filled in on my view by the user and the user pressed the submit button, I want to save the changes to the appropriate tables in my controller: (I've got an instance of MyViewModel named db)

[HttpPost] public ActionResult Submit(MyViewModel model)
{
  if (ModelState.IsValid)
  {
    db. //what do I do here?
  }
}

In tutorials and such, I've only seen one model at a time being used, therefore they can just do something like

db.People.Add(model);
db.SaveChanges();

With data being saved to multiple tables when the submit button is pressed by the user, I'm not sure how to save changes to each table in my ViewModel. Any assistance would be great! Thanks.

You'd just save the models that are properties on the view model. Using your example from a tutorial, if you were going to add a new record for each of those two, it might be something like this:

db.People.Add(model.People);
db.Organizations.Add(model.Organizations);
db.SaveChanges();

You can make all the additions/modifications/etc. that you want within the database context (the db object and its properties) and when you call .SaveChanges() they will all get sent to the database. In the above code that database call would end up being two INSERT statements.

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