将数据插入到多个表MVC ASP的最佳方法 [英] Best way to insert data to multiple table MVC ASP

查看:175
本文介绍了将数据插入到多个表MVC ASP的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 4 tables. OperationTable, ClientTable, ClientDetails, OperationRes

ClientTable

ClientTable

  • ClientID
  • 名称
  • 姓氏
  • 生日
  • VerNumber

ClientDetails

ClientDetails

  • ClientID
  • 电子邮件
  • 地址
  • 电话

OperationTable

OperationTable

  • OperationID
  • 日期
  • 时间
  • ClientID

OperationRes

OperationRes

  • ResID
  • OperationID
  • 名称
  • 类型

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

i have page where we ask Client to fill a form to register for smth. Everything must be in one page and after Client submit the form, we must insert all data to it's table. Date and Time to OperationTable, Name and Surname to ClientTable and so on. I'm new in ASP.NET MVC. i have tried to use "Code Fisrt". I have created Model and just used it to autogenerate View and Controller. but it's not what i want. i've found this Tutorial. it works! But i have more than 4 tables which and more rows than i write above. what is the best solution?

推荐答案

您想要一个包含要插入的所有数据的视图模型,然后在控制器中基于该视图模型创建对象并使用EF进行插入.像这样:

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
}

然后在您的控制器中,使用ViewModel填充您的实体,然后使用EF插入:

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.

这篇关于将数据插入到多个表MVC ASP的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆