Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 728
teynon Avatar asked Dec 20 '13 18:12

teynon


People also ask

How do you avoid duplicates in Entity Framework?

Duplicate rows in Entity Framework SQL View Entity Framework auto set fields as entity key for those not null column and return the row that match those entity key that causes the problem. You can set AsNoTracking option directly on your view to resolve this issue.

What causes duplicate entries?

Data aggregation and human typing errors are some of the sources of duplicate data. Customers may also provide a company with different information at different points in time. Hence, businesses should consider removing duplicate records from their Database.

What difference does AsNoTracking () make?

AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.


1 Answers

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.

like image 84
Slauma Avatar answered Oct 30 '22 22:10

Slauma