Entityframework duplicating when calling savechanges
c#, ef-code-first, entity-framework
Solution
I suspect that the context does not know that the Fabrics are not new items - so it adds/inserts them.
If you attach the fabrics to the DataContext (as Unchanged/NotModified) - or select them from the database, then when SaveChanges() is called the context knows about existing Fabric objects and can then just create a navigation relationship for the new FabricLineItem without creating a new Fabric
EF is a lot 'dumber' than it looks - you really need to tell it almost everything.
Problem
I am using entityframework 5 code first, I have a model like this. ``` class Product { public Product() { Fabrics = new BindingList<FabricLineItem>(); } ... public virtual ICollection<FabricLineItem> Fabrics { get;set; } } class FabricLineItem { [ForeignKey("Fabric")] public int FabricId { get; set; } public virtual Product Product { get;set; } public virtual Fabric Fabric { get;set; } } class Fabric { ... } ``` I already have fabrics in my database. I create a new product object and add some fabriclineitems to the collection. When I try to save product what happens is it duplicates the fabric in the database and reference it to the new one after calling ``` DataContext.SaveChanges(); ``` Before the call to savechanges the values in the debugger are correct by after calling they are changed ? Any idea why I am getting this strange behavior ?