Entity Framework Creates New / Duplicate Entries for Associated Objects

c# entity-framework

Question

I am trying to use Code First to create an SQL CE 4 database. When running the sample code below, Entity Framework is inserting new records for product each time, even though the data is exactly the same. What do I need to do to make Entity Framework not create duplicate associated products? The values in the ForeignID1 and the Product object are values that already exist in the database, but Entity Framework is wiping the ID I give it and adding a new ID.

namespace MyApp.Model
{
    public class MyThing
    {    
        public int ID { get; set; }

        [ForeignKey("Product")]
        public int ForeignID1{ get; set; }

        public virtual Product Product { get; set; }
    }
}

// Data.DataManager.cs

public class DataManager : DbContext
{
    public DbSet<Model.MyThing> Things{ get; set; }
    public DbSet<Model.Product> Products { get; set; }
}

These are the values it has entered. There should only be one value in the table that is referenced by multiple MyThings's

enter image description here

1
14
12/20/2013 6:57:51 PM

Accepted Answer

In order to avoid the duplication you must attach the related entity to the context:

context.Products.Attach(myThing.Product);
context.Things.Add(myThing);

Or...

myThing.Product = null;
context.Things.Add(myThing);

...will work as well if you have set myThing.ForeignID1 to an existing Product ID.

11
12/20/2013 7:28:23 PM


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