I have a First First EF 5.0 model that has the following structure:
public class Widget { public virtual Int32 Id { get; set; } public virtual String Name { get; set; } } public class Product { public virtual Int32 Id { get; set; } public virtual ICollection<Widget> Widgets { get; set; } public virtual AddWidget(Widget widget) { Guard.NotNull(widget); if (Widgets == null) { Widgets = new List<Widget>(); } Widgets.Add(widget); } }
When I try to save a new transitional Product with a few Widget added, only the first Widget saved:
// ProductManagementContext is a DbContext // ProductManagementContext.Products is a DbSet<Product> using(var context = new ProductManagementContext()) { var product = new Product(); product.AddWidget(new Widget() { Name = "Foo" } ); product.AddWidget(new Widget() { Name = "Bar" } ); context.Products.Add(product); context.SaveChanges(); }
At this point, only "Foo" exists in the Widget table. I used SQL Server Profiler to check the data coming into the database, and only one INSERT is issued for the first Widget in the collection, which has two added.
Why doesn't EF cascade on both new objects?
source share