Why does Entity Framework only cascade single item in a collection?
I have a Code First EF 5.0 model which 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 transient Product with more than one added
Widget, only the first Widget added is 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 going to the database, and only one INSERT
statement is issued for the first Widget in the collection that has two
added.
Why isn't EF cascading on both new entities?
No comments:
Post a Comment