Note that there are some explanatory texts on larger screens.

plurals
  1. POCode first add entity with many-to-many relationship
    primarykey
    data
    text
    <p>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.</p> <p>My customer class (simplified):</p> <pre><code>public partial class Customer { public virtual int Id { get; set;} public virtual string Name { get; set;} #region Navigation Properties public virtual ICollection&lt;CustomerType&gt; CustomerTypes { get; set; } #endregion } </code></pre> <p>Customer type:</p> <pre><code>public partial class CustomerType { public virtual int Id { get; set; } public virtual string Name { get; set; } #region Navigation Properties public virtual ICollection&lt;Customer&gt; Customers { get; set; } #endregion } </code></pre> <p>When I run this project a CustomerTypeCustomer table is created with columns Customer_Id and CustomerType_Id so this is fine.</p> <p>I then create the customer like so:</p> <pre><code>// code behind var customer = new Customer(); customer.name = txtCustomerName.Text; using (var context = new MyEntities()) { context.Customers.Add(customer); context.SaveChanges(); } </code></pre> <p>I had a look here <a href="https://stackoverflow.com/questions/4253165/insert-update-many-to-many-entity-framework-how-do-i-do-it">Insert/Update Many to Many Entity Framework . How do I do it?</a> and tried to do something similar with customer types:</p> <pre><code>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 =&gt; 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(); } </code></pre> <p>Am I missing something obvious here?</p> <p>Thanks in advance.</p> <p>Edit: for some reason I only have .Add( no AddToObject, AttachTo etc.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload