Entityframework duplicating when calling savechanges

c# ef-code-first entity-framework

Question

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 ?

1
5
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.

6
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:

context.Fabrics.Attach(product.Fabric); 
context.Products.Add(product);
context.SaveChanges();

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."

http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx



Related Questions





Related

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