Skip to content

Why is DistinctBy not working in EFCore ?

Solution/Workaround

As roji a principal software engineer at microsoft said in a github issue concerning this problem.

we can translate the query into the next statement which will work for simple cases:

cs
_ = blogs.DistinctBy(b => b.Id);

_ = blogs.GroupBy(b => b.Id).Select(g => g.First());


the two above statements are equivalent, but for more complex queries this might not always work or return the expected result. make sure to inspect the SQL that is generated for this query to see if you got the correct behavior you wanted.


you can see the sql generated by the query using the ToQueryString() function.

cs
var sql = blogs.GroupBy(b => b.Id).Select(g => g.First()).ToQueryString();

Thanks for reading, hope it was useful.