0

我有一个对象 Customer,它可以有多个客户类型,每个客户类型可以有多个客户。我是 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
}

当我运行这个项目时,会创建一个包含 Customer_Id 和 CustomerType_Id 列的 CustomerTypeCustomer 表,所以这很好。

然后我像这样创建客户:

// 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 。我该怎么做?并尝试对客户类型做类似的事情:

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 等。

4

2 回答 2

0

您必须先初始化CustomersTypes集合。

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

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

于 2012-07-02T08:00:49.207 回答
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();  
}
于 2012-07-02T08:07:58.673 回答