Best way to insert data to multiple table MVC ASP

让人想犯罪 __ 提交于 2019-11-30 03:57:18

You want a view model that holds all the data you want to insert, then in your controller create the objects based on that view model and insert using EF. Something like:

public class MyViewModel
{
    public string Name {get; set;}
    public string Birthday {get; set;}
    public string VerNumber { get; set;}
    public string Email {get; set;}
    public string Address {get; set;}
    // etc etc for the rest of your data
}

Then in your controller, use your ViewModel to populate your entities, then insert using EF:

[HttpPost]
public ActionResult Add(MyViewModel model)
{
     var client = new Client{
          Name = model.Name,
          Birthday = model.Birthday
     };

     var clientDetails = new ClientDetails();

     //etc for your other entities

     using (var context = new MyDbContext)
     {
          context.Clients.Add(client);
          clientDetails.ClientId = client.Id;
          context.ClientDetails.Add(clientDetails);
          //etc add your other classes
          context.SaveChanges();

     }

     //whatever you want to do here for the result, maybe direct to new controller
     //or return view
     return View();

}

You may want to look at tidying up the entity framework code using a Repository Pattern and you could also look at automapper to map entities from your viewmodel, to save doing it manually.

Logically, your operation will be exactly same as the tutorial show. only you have to create ViewModel which contains all the 4 table fields.

Then when the form post back, do your logic of deciding which field in ViewModel goes to which tables' model. Then save that table model.

In the tutorial it use one ViewModel (LoginViewModel) and save to two table (Login, User). In you case just save to 4 (OperationTable, ClientTable, ClientDetails, OperationRes).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!