Error EF Distinct (IEqualityComparer)

.net c# c#-3.0 entity-framework linq-to-entities

Question

Happy morning!

Given:

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 build, but when I run it, I'll get anLinq to Entity could not translate Comparer -Exception.
Any recommendations?

1
14
6/18/2009 5:41:40 AM

Accepted Answer

To provide your own comparisons, you must carry out theDistinct in.NET code call. Use to ensure that takes place.AsEnumerable to pivotIQueryable<T> into IEnumerable<T> :

var result = myEntity.MyDomainEntity
        .Where(myDomainEntity => myDomainEntity.MySpecialID > default(int))
        .AsEnumerable()
        .Distinct(new FooComparer());

Naturally, you'll then be transferring additional data from the database. The data might also be grouped as an alternative:

var result = from entity in myEntity.MyDomainEntity
             where entity.MySpecialID > 0
             group entity by entity.MySpecialID into groups
             select groups.FirstOrDefault();

If my query-fu isn't failing me, you'll receive the first object associated with each ID. Distinct already does essentially that, however everything is done at the database.

(Note to future readers: contactingFirst() more logical thanFirstOrDefault() , yet evidently that is ineffective.)

32
6/22/2009 8:24:05 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow