Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Query Results Duplicate

  • I created a SQL View that joins a few tables and when tested in SQL Manager it provides the correct data (If a makes a difference these are complex joins).
  • In MVC I created a (data first) Entity Data Model and then added code generation.
  • I have a LINQ query in a controller that generates an idex page.

All basic MVC stuff.

When I run the application I receive duplicate records. To further qualify, if an order has more than one line it returns the first record for each line in the "order".

SQL Results
Order, Line, Part
12345, 1, 3829138120
12345, 2, 1238401890

MVC/EF Results
Order, Line
12345, 1, 3829138120
12345, 1, 3829138120

Any thoughts as to the cause of this problem?

like image 743
Pete Avatar asked Oct 31 '11 15:10

Pete


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

How to avoid inserting duplicate records in mvc?

best way is to query for a record with the same FirstName (using FirstOrDefault() to get only the first one or better Count()) and do not even try to insert the record. Adriano, thanks for your answers.


1 Answers

You should double check the entity key attributes. I see your query result and you should mark as primary key Order and Line and I think that you have forget mark order as key.

like image 130
dani herrera Avatar answered Oct 02 '22 06:10

dani herrera