I am having problems with EF changing my inserts when trying to add an entity with multiple children at the same time. I have a 3-level structure with a one-to-many relationship between each ( Outer 1--* Item 1--* SubItem ). If I try to insert a new Outer with elements and subelements, elements containing SubItems will be inserted first.
Sample code (.NET 4.5, EF 5.0.0-rc):
public class Outer { public int OuterId { get; set; } public virtual IList<Item> Items { get; set; } } public class Item { public int OuterId { get; set; } [ForeignKey("OuterId")] public virtual Outer Outer { get; set; } public int ItemId { get; set; } public int Number { get; set; } public virtual IList<SubItem> SubItems { get; set; } } public class SubItem { public int SubItemId { get; set; } [ForeignKey("ItemId")] public virtual Item Item { get; set; } public int ItemId { get; set; } } public class MyContext : DbContext { public DbSet<Outer> Outers { get; set; } public DbSet<Item> Items { get; set; } public DbSet<SubItem> SubItems { get; set; } } class Program { static void Main(string[] args) { Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>()); MyContext context = new MyContext(); // Add an Outer object, with 3 Items, the middle one having a subitem Outer outer1 = new Outer { Items = new List<Item>() }; context.Outers.Add(outer1); outer1.Items.Add(new Item { Number = 1, SubItems = new List<SubItem>() }); outer1.Items.Add(new Item { Number = 2, SubItems = new List<SubItem>(new SubItem[] { new SubItem() }) }); outer1.Items.Add(new Item { Number = 3, SubItems = new List<SubItem>() }); context.SaveChanges(); // Print the order these have ended up in foreach (Item item in context.Items) { Console.WriteLine("{0}\t{1}", item.ItemId, item.Number); } // Produces output: // 1 2 // 2 1 // 3 3 } }
I know this answer from Alex James , which says that inserts may need to be reordered in order to satisfy relational constraints, but this is not a problem here. His answer also mentions that they cannot track the order of elements in order preserving structures such like lists.
I would like to know how I can order these inserts. Although I can rely on sorting my inserted elements by a field other than a PC, it is much more efficient if I can rely on the PK order. I really don't want to use multiple SaveChanges calls to accomplish this.
I use the EF5 RC, but judging by other unanswered questions, this has been around for some time!
entity-framework-5 entity-framework
Richard
source share