Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework 4.1 Code-First and Inserting New One-to-Many Relationships
    text
    copied!<p>I am having trouble peristing a new object graph to the context with a one-to-many relationship. I am using the Entity Framework 4.1 release, and implementing a Code-First approach. I am using an existing SQL 2008 database and implemented a context derived from DbContext. I have two classes, Person and Address. A person can contain 0 or more Addresses, defined as such.</p> <pre><code>public class Person { public Person() { Addresses = new List&lt;Address&gt;(); } public int PersonId { get; set; } ***Additional Primitive Properties*** public virtual ICollection&lt;Address&gt; Addresses { get; set; } } public class Address { public int AddressId { get; set; } public int AddressTypeId { get; set; } ***Additional Primitive Properties*** public int PersonId { get; set; } public virtual Person Person { get; set; } } </code></pre> <p>I am trying to create a new instance of Person with two addresses. However, when I add this structure to the context and save, only the first Address in the collection is persisted. The second has the Person navigation property set to null, and is not associated with the Person object, however, the first one in the list is associated.</p> <pre><code>var person = new Person(); var mailingAddress = new Address() { AddressTypeId = 1 }; person.Addresses.Add(mailingAddress); var billingAddress = new Address() { AddressTypeId = 2 }; person.Addresses.Add(billingAddress); context.People.Add(entity); context.SaveChanges(); </code></pre> <p>It does not throw an exception, but the second item in the Address collection is just not saved.</p> <p>Does anybody have any good ideas on why only the first would be saved? Thank you.</p>
 

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