0

I have been given this solution in one of my question... seems very interesting.. as i am trying and learning to understand LINQ.. I am having this error while implementing this. I dont know whats going wrong here... seeking expert advice.

public class CategotiesEqualityComparer : IEqualityComparer<ac_Categories>
{
    public bool Equals(ac_Categories x, ac_Categories y)
    {
        return x.ThumbnailAltText.Trim() == y.ThumbnailAltText.Trim();
    }

    public int GetHashCode(ac_Categories obj)
    {
        return obj.ThumbnailAltText.Trim().GetHashCode();
    }
}

var catlist = _db.ac_Categories
.Where(c => c.VisibilityId == 0 && c.ThumbnailAltText != null
    && (!c.ThumbnailAltText.StartsWith("gifts/")
    && !c.ThumbnailAltText.StartsWith("email/")
    && !c.ThumbnailAltText.StartsWith("news/")
    && !c.ThumbnailAltText.StartsWith("promotions/")
    && !c.ThumbnailAltText.StartsWith("the-knowledge/")))
    .Distinct(new CategotiesEqualityComparer()).ToList();

ERROR:LINQ to Entities does not recognize the method 'System.Linq.IQueryable1[WebMgr.ac_Categories] Distinct[ac_Categories](System.Linq.IQueryable1[WebMgr.ac_Categories], System.Collections.Generic.IEqualityComparer`1[WebMgr.ac_Categories])' method, and this method cannot be translated into a store expression

NOTE:

I am using Database first approach and ac_Categories is created using that...

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
patel.milanb
  • 5,822
  • 15
  • 56
  • 92

1 Answers1

4

You can't pass an IEqualityComparer comparer into a call to an EF query or likely most IQueryable collections. IQueryable are expression trees, that expression tree gets converted into an underlying query (such as SQL with EF). As such it can't execute your code in SQL.

A normal Distinct() call will work just fine if you want to filter out duplicate identical records as it will perform a SQL distinct. If you it to apply your equality comparer you would have to pull the data into memory then apply your distinct.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ben Robinson
  • 21,601
  • 5
  • 62
  • 79