C# 代码首先添加具有多对多关系的实体

C# 代码首先添加具有多对多关系的实体,c#,asp.net,entity-framework,entity-framework-4,C#,Asp.net,Entity Framework,Entity Framework 4,我有一个对象客户,可以有多个客户类型,每个客户类型可以有多个客户。我是EF的新手,但已经成功添加了一个客户,但似乎无法获得添加客户的客户类型的正确语法 我的客户类别(简化): 我在这里查看了一下,并尝试对客户类型执行类似的操作: var customer = new Customer(); customer.name = txtCustomerName.Text; // only starting with one customer type selected in a check box l

我有一个对象客户,可以有多个客户类型,每个客户类型可以有多个客户。我是EF的新手,但已经成功添加了一个客户,但似乎无法获得添加客户的客户类型的正确语法

我的客户类别(简化):

我在这里查看了一下,并尝试对客户类型执行类似的操作:

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();  
}
我是不是漏掉了什么明显的东西

提前谢谢


编辑:由于某些原因,我只有.Add(无AddToObject、AttachTo等)

您必须首先初始化
CustomerType
集合

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

您还可以将此初始化添加到
客户的构造函数中。

这是一种方法:

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();  
}
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();  
}
customer.CustomerTypes = new List<CustomerType>();
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();  
}