2012-07-02 115 views
0

我有一个对象客户可以有多个客户类型,每个客户类型可以有多个客户。我是EF的新手,但设法添加了一位客户,但似乎无法获得添加客户的客户类型的语法。代码第一次添加多对多关系的实体

我的客户类(简体):

public partial class Customer 
{ 
     public virtual int Id { get; set;} 
     public virtual string Name { get; set;} 

    #region Navigation Properties 

     public virtual ICollection<CustomerType> CustomerTypes 
     { get; set; } 

    #endregion 
} 

客户类型:

public partial class CustomerType 
{ 

     public virtual int Id 
     { 
      get; 
      set; 
     } 

     public virtual string Name 
     { 
      get; 
      set; 
     } 

     #region Navigation Properties 

     public virtual ICollection<Customer> Customers 
     { get; set; } 

     #endregion 
} 

当我运行这个项目CustomerTypeCustomer表与列CUSTOMER_ID和CustomerType_Id创建的,因此,这是好的。

我然后创建客户像这样:

// code behind 
var customer = new Customer(); 
customer.name = txtCustomerName.Text; 

using (var context = new MyEntities()) 
{ 
    context.Customers.Add(customer); 
    context.SaveChanges(); 
} 

我这里Insert/Update Many to Many Entity Framework . How do I do it?看了一下,并试图做类似的客户类型的东西:

var customer = new Customer(); 
customer.name = txtCustomerName.Text; 

// only starting with one customer type selected in a check box list 
CustomerType customerType = context.CustomerTypes.FirstOrDefault(i => i.Id == 1); 

using (var context = new MyEntities()) 
{ 
    // IncidentTypes throws Object reference not set to an instance of an object 
    customer.CustomerTypes.add(customerType); 

    context.Customers.Add(customer); 
    context.SaveChanges(); 
} 

我失去的东西在这里很明显?

在此先感谢。

编辑:由于某种原因,我只。新增(无AddToObject,AttachTo等

回答

0

必须初始化CustomersTypes收集第一

customer.CustomerTypes = new List<CustomerType>(); 

您也可以此初始化添加到您的Customer的。 。构造

+0

谢谢,那是失踪的一块 –

0

这是做这件事:

var customer = new Customer(); 
customer.name = txtCustomerName.Text; 

// only starting with one customer type selected in a check box list 
//add Include there 
CustomerType customerType = context.CustomerTypes.Include("Customers").FirstOrDefault(i => i.Id == 1); 

using (var context = new MyEntities()) 
{ 
    // IncidentTypes throws Object reference not set to an instance of an object 
    //customer.CustomerTypes.add(customerType); 

    //context.Customers.Add(customer); 
    customerType.Customers.Add(customer); 
    context.SaveChanges(); 
} 
相关问题