我有一个客户,可以有多种客户类型,每种客户类型可以有多个客户。我是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();
}
我错过了一些明显的东西吗?
提前致谢。
编辑:出于某种原因我只有.Add(没有AddToObject,AttachTo等。
答案 0 :(得分:0)
您必须先初始化CustomersTypes
集合。
customer.CustomerTypes = new List<CustomerType>();
您也可以将此初始化添加到Customer
的构造函数中。
答案 1 :(得分: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();
}