1

我一直在努力在 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; }

在这种情况下,一位客户通过外键参考获得多个联系方式。请任何人指导我实现这一目标。谢谢并提前。

4

2 回答 2

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; }
于 2013-08-02T07:09:58.927 回答
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();
于 2013-08-02T07:50:33.000 回答