0

I have an object Customer that can have multiple customer types and each customer type can have multiple customers. I'm new to EF but have managed to add a customer, but can't seem to get the syntax right for adding the customer's customer types as well.

My customer class (simplified):

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
}

Customer type:

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
}

When I run this project a CustomerTypeCustomer table is created with columns Customer_Id and CustomerType_Id so this is fine.

I then create the customer like so:

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

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

I had a look here Insert/Update Many to Many Entity Framework . How do I do it? and tried to do something similar with customer types:

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();  
}

Am I missing something obvious here?

Thanks in advance.

Edit: for some reason I only have .Add( no AddToObject, AttachTo etc.

Community
  • 1
  • 1
John Doe
  • 188
  • 1
  • 14

2 Answers2

0

You must initialize CustomersTypes collection first.

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

You can also add this initialization to your Customer's constructor.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
0

This is one way to do it:

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();  
}