LINQ to Entities无法识别方法'Boolean Contains

Sim*_*ons 2 .net iequalitycomparer c#-4.0

我写了这样的声明:

if (!db.Customers.Contains<Customer>(customer,customerCompairor))
                {
                    db.Customers.Add(customer);
                }
Run Code Online (Sandbox Code Playgroud)

看不出有以下错误的原因:

LINQ to Entities无法识别方法'Boolean Contains [Customer](System.Linq.IQueryable 1[DBInteractor.Customer], DBInteractor.Customer, System.Collections.Generic.IEqualityComparer1 [DBInteractor.Customer])'方法,并且此方法无法转换为商店表达式.

我创建了一个参考:

  IEqualityComparer<Customer> customerCompairor = new PMKeyCompairor();
Run Code Online (Sandbox Code Playgroud)

和PMKeyCompairor正在实施 IEqualityComparer<Customer>

class PMKeyCompairor:IEqualityComparer<Customer>
    {
            ........................
            .............................
     }
Run Code Online (Sandbox Code Playgroud)

客户有一个扩展方法Contains(返回一个bool)DbSet.

那我哪里错了?

Tho*_*que 9

Linq to Entities查询被转换为SQL,但无法将自定义比较器的逻辑转换为SQL,因此必须在内存中进行比较.你可以这样做:

if (!db.Customers.AsEnumerable().Contains<Customer>(customer,customerCompairor))
Run Code Online (Sandbox Code Playgroud)

但它会将每个客户加载到内存中,然后再将其与customer变量进行比较,这可能不是一个好主意......

如果可以,尝试将比较逻辑表示为内联Linq表达式,例如:

if (!db.Customers.Any(c => c.Id == customer.Id && c.Name == customer.Name))
Run Code Online (Sandbox Code Playgroud)