teynon
teynon

Reputation: 8288

Entity Framework Creates New / Duplicate Entries for Associated Objects

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

Upvotes: 17

Views: 17760

Answers (1)

Slauma
Slauma

Reputation: 177133

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.

Upvotes: 14

Related Questions