.net - LINQ to Entities 无法识别“Boolean Contains”方法

标签 .net c#-4.0 iequalitycomparer

我写了这个声明:

if (!db.Customers.Contains<Customer>(customer,customerCompairor))
                {
                    db.Customers.Add(customer);
                }

看不到出现以下错误的原因:

LINQ to Entities does not recognize the method 'Boolean Contains[Customer](System.Linq.IQueryable1[DBInteractor.Customer], DBInteractor.Customer, System.Collections.Generic.IEqualityComparer1[DBInteractor.Customer])' method, and this method cannot be translated into a store expression.

我已经创建了一个引用:

  IEqualityComparer<Customer> customerCompairor = new PMKeyCompairor();

PMKeyCompairor 正在实现 IEqualityComparer<Customer>

class PMKeyCompairor:IEqualityComparer<Customer>
    {
            ........................
            .............................
     }

Customers 有一个扩展方法 Contains(返回一个 bool 值),因为它是 DbSet .

那么我哪里出错了?

最佳答案

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

if (!db.Customers.AsEnumerable().Contains<Customer>(customer,customerCompairor))

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

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

if (!db.Customers.Any(c => c.Id == customer.Id && c.Name == customer.Name))

关于.net - LINQ to Entities 无法识别“Boolean Contains”方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17404832/

相关文章:

.net - 如何停止Backgroundworker并关闭表单?

xml - 如何使用重复的 XMLNodes 反序列化此 xml

c# - Visual Studio 2010 : How to enforce build order of projects in a solution?

c# - 如何实现具有容差的 IEqualityComparer<PointF>

c# - 检测移动设备上 .NET/Mono 的内存不足情况

c# - ASP.Net session 问题

c# - 访问类的私有(private)成员

.net - 免费 Codesmith 替代品?

c# - 什么时候应该使用 IEqualityComparer? C#

c# - SequenceEqual 的 IEqualityComparer