Yesterday I was working on a code refactor and came across an exception that I really couldn\'t find much information on. Here is the situation.
We have an a pair of
I think you stumbled upon a bug in Entity Framework. EF has some logic for picking an appropriate concrete type to materialize collections. HashSet<T>
is one of its favorites. Apparently (I can't fully follow EF's source code here) it picks HashSet for ICollections and List for IEnumerable.
It looks like EF tries to create a HashSet by using the constructor that accepts an IEqualityComparer<T>
. (This happens in EF'sDelegateFactory
class, method GetNewExpressionForCollectionType
.) The error is that it uses its own ObjectReferenceEqualityComparer
for this. But that's an IEqualityComparer<object>
, which can not be converted to an IEqualityComparer<int>
.
In general I think it is best practice not to use ToList
in LINQ queries and to use IEnumerable
in collections in DTO types. Thus, EF will have total freedom to pick an appropriate concrete type.