I have written this statement:
if (!db.Customers.Contains<Customer>(customer,customerCompairor))
{
db.Customers.Add(customer);
}
Don't see a reason why getting following error:
LINQ to Entities does not recognize the method 'Boolean Contains[Customer](System.Linq.IQueryable
1[DBInteractor.Customer], DBInteractor.Customer, System.Collections.Generic.IEqualityComparer
1[DBInteractor.Customer])' method, and this method cannot be translated into a store expression.
I have created a reference :
IEqualityComparer<Customer> customerCompairor = new PMKeyCompairor();
and PMKeyCompairor is implementing IEqualityComparer<Customer>
class PMKeyCompairor:IEqualityComparer<Customer>
{
........................
.............................
}
Customers has an extension method Contains (returns a bool) as it's DbSet
.
So where am I going wrong?
Linq to Entities queries are translated to SQL, but there is no way to translate the logic of your custom comparer to SQL, so the comparison has to be done in memory. You could do something like that:
if (!db.Customers.AsEnumerable().Contains<Customer>(customer,customerCompairor))
But it would load each customer in memory before comparing it to the customer
variable, which is probably not a very good idea...
If you can, try to express the comparison logic as an inline Linq expression, e.g.:
if (!db.Customers.Any(c => c.Id == customer.Id && c.Name == customer.Name))