将数据插入多个表MVC ASP的最佳方法

DSI*_*DSI 11 asp.net asp.net-mvc asp.net-mvc-4 entity-framework-5

我有4张桌子.OperationTable,ClientTable,ClientDetails,OperationRes

ClientTable

  • 客户端ID
  • 名称
  • 生日
  • VerNumber

ClientDetails

  • 客户端ID
  • 电子邮件
  • ADRESS
  • 电话

OperationTable

  • OperationID
  • 日期
  • 时间
  • 客户端ID

OperationRes

  • 渣油
  • OperationID
  • 名称
  • 类型
  • 没有

我有页面要求客户填写表格以注册smth.一切都必须在一个页面中,在客户提交表单后,我们必须将所有数据插入到表中.OperationTable的日期和时间,ClientTable的名称和姓氏等.我是ASP.NET MVC的新手.我曾尝试使用"Code Fisrt".我创建了Model并且只是用它来自动生成View和Controller.但这不是我想要的.我找到了这个教程.有用!但我有超过4个表,比上面写的更多行.什么是最好的解决方案?

小智 18

您需要一个包含要插入的所有数据的视图模型,然后在控制器中根据该视图模型创建对象并使用EF插入.就像是:

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
}
Run Code Online (Sandbox Code Playgroud)

然后在您的控制器中,使用ViewModel填充您的实体,然后使用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();

}
Run Code Online (Sandbox Code Playgroud)

您可能希望使用存储库模式来查看整理实体框架代码 ,您还可以查看automapper以从viewmodel映射实体,以便手动保存.