我写了这个声明:
if (!db.Customers.Contains<Customer>(customer,customerCompairor))
{
db.Customers.Add(customer);
}
看不到出现以下错误的原因:
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.
我已经创建了一个引用:
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/