我有一個對象客戶可以有多個客戶類型,每個客戶類型可以有多個客戶。我是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等
謝謝,那是失蹤的一塊 –