Exception on Inner LINQ query when calling ToList()

前端 未结 1 433
太阳男子
太阳男子 2020-12-11 16:34

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

相关标签:
1条回答
  • 2020-12-11 17:19

    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.

    0 讨论(0)
提交回复
热议问题