Entityframework duplicating when calling savechanges

c# ef-code-first entity-framework


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 {
    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


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 ?

3/13/2013 7:04:35 PM

Accepted Answer

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.

3/14/2013 8:37:22 AM

Popular Answer

I was also having the problem of E.F. not recognising that an item already existed when it was referenced within another new object to be added to the DB.

@NeilThompson gave me the clue above how to solve this:

You need to attach an existing entity to the context so that it knows that it already exists:

For example:


return organisation;

I got this from here:

"If you have an entity that you know already exists in the database but which is not currently being tracked by the context then you can tell the context to track the entity using the Attach method on DbSet. The entity will be in the Unchanged state in the context."


Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow