Question

I have been trying for hours to get a Distinct to work for my code.

I am using EF 4.3, MVC3, Razor and trying to get a list downto product id and name. When I run the Sql query against the DB, it's fine.

Sql Query is

SELECT DISTINCT [ProductId]
      ,[Product_Name]
  FROM [dbo].[PRODUCT]

The only other column in that table is a country code so that's why a standard distinct() isn't working.

I have gone as far as creating an IEqualityComparer

Here is code:

public class DistinctProduct : IEqualityComparer<PRODUCT>
    {
        public bool Equals(PRODUCT x, PRODUCT y)
        {
            return x.ProductId.Equals(y.ProductId);
        }

        public int GetHashCode(PRODUCT obj)
        {
            return obj.ProductId.GetHashCode();
        }
    }

here is where I called it.

IEqualityComparer<PRODUCT> customComparer = new DistinctProduct();
IEnumerable<PRODUCT> y = db.PRODUCTs.Distinct(customComparer);

But when it hit's that Last line I get an error out of it stating...

LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[MyService.Models.PRODUCT] Distinct[PRODUCT](System.Linq.IQueryable`1[MyService.Models.PRODUCT], System.Collections.Generic.IEqualityComparer`1[MyService.Models.PRODUCT])' method, and this method cannot be translated into a store expression.

Can anyone tell me what I'm doing wrong?

Thanks,

David

Was it helpful?

Solution

Entity Framework is trying to translate your query to a SQL query. Obviously it does not know how to translate the IEqualityComparerer. I think the question is whether you want to do the Distinct in the datbase (in which case your client gets only filtered results) or you are OK with bringing all the data to the client and select distinct on the client. If you want the filtering to happen on the database side (which will make your app perform much better) and you want to be able to use different strategies for comparing you can come up with a code that builds distinct criteria on top of your query. If you are fine with bringing your data to the client (note that it can be a lot of data) you should be able just to do (.ToList() will trigger querying the database and materializing results):

IEnumerable<PRODUCT> y = db.PRODUCTs.ToList().Distinct(customComparer);

OTHER TIPS

Is there any reason you could just not use a distinct like the following?

var distinctProdcts = (from p in db.PRODUCTs
                       select new { 
                           ProductId = p.ProductId, 
                           Product_Name = p.ProductName 
                      }).Distinct();

This would remove the country code from the query before you do the distinct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top