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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With