早上好!
假设:
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();
}
}
这将编译,但在运行时我会得到一个Linq to Entity could not translate Comparer
- 例外
有什么建议吗?
答案 0 :(得分:31)
如果您提供自己的比较,则需要在.NET代码中执行Distinct
调用。要确保发生这种情况,请使用AsEnumerable
将IQueryable<T>
转换为IEnumerable<T>
:
var result = myEntity.MyDomainEntity
.Where(myDomainEntity => myDomainEntity.MySpecialID > default(int))
.AsEnumerable()
.Distinct(new FooComparer());
当然,此时您将从数据库中提取更多数据。另一种方法是改为对数据进行分组:
var result = from entity in myEntity.MyDomainEntity
where entity.MySpecialID > 0
group entity by entity.MySpecialID into groups
select groups.FirstOrDefault();
这将使您获得每个ID遇到的第一个实体(假设我的查询 - fu没有让我失望)。这基本上就是Distinct所做的,但它都在数据库中。
(请注意未来的读者:调用First()
比FirstOrDefault()
更有意义,但显然这不起作用。)