I have a strange problem with Linq to Entities sometimes generating graphs with duplicates. A query, using includes, with a simple restriction at the base of the graph requested does not generate duplicates.
When the same query is used with another restriction elsewhere in the graph I have duplicates.
Consider the following graph :
Entity1
Entity2
Entity3
Entity4
Entity5
Entity6
Entity7
Entity8
Now, this query :
var query = context.Entity1.Where(u => (u.StringProp.StartsWith(someValue)));
query = query.Include(@"NavpropEntity2.NavPropEntity3.NavPropEntity4.NavPropEntity5.NavEntity6");
query = query.Include(@"NavpropEntity2.NavPropEntity3.NavPropEntity7");
query = query.Include(@"NavpropEntity2.NavPropEntity3.NavPropEntity8");
does not generated duplicates for entity6 in the graph.
But the following query does !
query = context.Entity1.Join(context.Entity3, u => u.Entity2.Entity3.Entity4Id, g => g.Id, (u, g) => new NotSoAnonymousTypeWithParameterLessConstructor { Entity4= g, Entity1 = u })
.Where(
ApplyNotSoAnonymousTypeRestrictions(
StringProp,
Id)
).Select(z => z.Entity1);
query = query.Include(@"Navprop1.NavProp2.NavProp3.NavProp4.NavProp5");
query = query.Include(@"Navprop1.NavProp2.NavProp3.NavProp6");
query = query.Include(@"Navprop1.NavProp2.NavProp3.NavProp7");
generates duplicates for Entity6.
Please note that the entity graph have the issue right at the end of the linq query. So this is an EF/STE issue not a STE issue.
This is an issued when the graph is sent back to the server to persist changes as explained in this blog post.
I hope someone encountered the same problem and have found a solution. TIA.
The problem arise when using the AsNoTracking() Extension introduced in EF5. This has nothing to do with the query structure. My data access code is generated from templates (.tt), we encountered the same problem today and I was able to compare one method that returned no duplicates with another one that was. The only difference was that.