EF独特(IEqualityComparer)错误 [英] EF Distinct (IEqualityComparer) Error
问题描述
早安!
给定:
public class FooClass
{
public void FooMethod()
{
using (var myEntity = new MyEntity)
{
var result = myEntity.MyDomainEntity.Where(myDomainEntity => myDomainEntity.MySpecialID > default(int)).Distinct(new FooComparer);
}
}
}
public class FooComparer : IEqualityComparer<MyEntity.MyDomainEntity>
{
public bool Equals(MyEntity.MyDomainEntity x, MyEntity.MyDomainEntity y)
{
return x.MySpecialID == y.MySpecialID;
}
public int GetHashCode(MyEntity.MyDomainEntity obj)
{
return obj.MySpecialID.GetHashCode();
}
}
这将编译,但在运行时我会得到一个
This will compile, but on runtime I will get an Linq to Entity could not translate Comparer
-Exception.
Any suggestions?
推荐答案
如果您提供自己的比较,您需要执行.NET代码中的 Distinct
调用。为了确保发生这种情况,请使用 AsEnumerable
将 IQueryable< T>
转换为 IEnumerable< T& ;
:
If you're providing your own comparisons, you'll need to execute the Distinct
call in .NET code. To make sure that happens, use AsEnumerable
to turn IQueryable<T>
into IEnumerable<T>
:
var result = myEntity.MyDomainEntity
.Where(myDomainEntity => myDomainEntity.MySpecialID > default(int))
.AsEnumerable()
.Distinct(new FooComparer());
当然这时你会从数据库中拉出更多的数据。另一种方法是对数据进行分组:
Of course at that point you'll be pulling more data across from the database. An alternative is to group the data instead:
var result = from entity in myEntity.MyDomainEntity
where entity.MySpecialID > 0
group entity by entity.MySpecialID into groups
select groups.FirstOrDefault();
这将让你成为每个ID遇到的第一个实体(假设我的查询不是失败的我)。这基本上是什么Distinct,反正,但它都在数据库。
That will get you the first entity encountered with each ID (assuming my query-fu isn't failing me). That's basically what Distinct does anyway, but it's all at the database.
(注意未来的读者:调用 First()
比 FirstOrDefault()
更有意义,但显然不起作用。)
(Note to future readers: calling First()
makes more sense than FirstOrDefault()
, but apparently that doesn't work.)
这篇关于EF独特(IEqualityComparer)错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!