Why does the Entity Framework only cascade a single item in a collection?

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?

+4
source share
2 answers

Your problem does not reproduce with the code shown. I copied and pasted a lot, fixed the compilation problem (AddWidget needs a return type), deleted the Guard call, launched it and saw that both widgets are displayed in the database.

Here is the complete code. Hope you can determine where your code is different.

 using System; using System.Collections.Generic; using System.Data.Entity; namespace EF_SO_Q { class Program { static void Main(string[] args) { 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(); } } } 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 void AddWidget(Widget widget) { if (Widgets == null) { Widgets = new List<Widget>(); } Widgets.Add(widget); } } public class ProductManagementContext : DbContext { public DbSet<Widget> Widgets { get; set; } public DbSet<Product> Products { get; set; } } } 
+1
source

I'm not sure, but I think this is because of the virtual keyword in id.

First you said code, and the key in db is an immutable property. Overriding this setting is confusing and probably wrong ...

Also, lists of sub-elements are defined as follows: this.Widgets = new HashSet<Widget>(); which is a more general list ... I'll take a picture

Ps I used the first model

0
source

Source: https://habr.com/ru/post/1495655/


All Articles