我一直在努力为客户及其联系人在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; }
在此方案中,一位客户使用外键引用获取多个联系人详细信息。请任何人指导我实现这一目标。谢谢并提前。
答案 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();