如何在MVC 4代码中首先实现主细节表数据插入

时间:2013-08-02 06:39:12

标签: asp.net-mvc-4

我一直在努力为客户及其联系人在MVC 4 EF代码中首先实现以下逻辑。


客户表

 public int ID { get; set; }

 public string Name{ get; set; }

 public string Address { get; set; }

customer_contact表

 public int CustomerID { get; set; }

 public string ContactName { get; set; }

 public string PhoneNo { get; set; }

 public string Email { get; set; }

在此方案中,一位客户使用外键引用获取多个联系人详细信息。请任何人指导我实现这一目标。谢谢并提前。

2 个答案:

答案 0 :(得分:0)

如果我们考虑EF中的一对多关系,您的设计应如下所示

客户表(假设客户类)

 public int CustomerID { get; set; }

 public string Name{ get; set; }

 public string Address { get; set; }

 public List<CustomerDetail> CustomerDetails{get; set; }

customer_contact表(假设 CustomerDetail 类)

 public int CustomerDetailId{ get; set; }

 public string ContactName { get; set; }

 public string PhoneNo { get; set; }

 public string Email { get; set; }

 public int CustomerID { get; set; }

 public Customer Customer {get; set; }

答案 1 :(得分:0)

您需要添加导航属性以允许您进行主/细节插入:

Customer课程中:

public virtual ICollection<CustomerDetail> CustomerDetails{ get; set; }

CustomerDetails课程中:

public virtual Customer Customer { get; set; }

然后向客户插入详细信息:

var customer = new Customer { Name="", Address="" };
context.Customers.Add(customer);

var customerDetails = new CustomerDetails { ContactName="", Customer=customer };
context.CustomerDetails.Add(customerDetails);

context.SaveChanges();