我正在使用ENtity Framework和Code First。我有一个传递给函数的对象列表,它将使用DatabaseContext中的Intersect函数并传递对象。它不起作用。这是代码:
public void BeginProcess(IEnumerable<Contract> selectedContracts)
{
DatabaseContext dc= new DatabaseContext();
var contract = dc.Contracts.Intersect<Contract>(selectedContracts, new ContractComparer());
foreach (var item in contract)
{
item.BatchNumber = 10;
}
//odc.Contracts.Intersect(selectedContracts).ToList().ForEach(x=>x.BatchNumber = batchNum);
odc.SaveChanges();
}
我创建了一个实现IEqualityComparer的ContractComparer类:
public class ContractComparer : IEqualityComparer<Contract>
{
#region IEqualityComparer<Contract> Members
public bool Equals(Contract x, Contract y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.OID == y.OID;
}
public int GetHashCode(Contract obj)
{
return base.GetHashCode();
}
#endregion
}
我得到的错误是:
LINQ to Entities无法识别方法'System.Linq.IQueryable 1[Contract] Intersect[Contract](System.Linq.IQueryable
1 [Contract],System.Collections.Generic.IEnumerable 1[Contract], System.Collections.Generic.IEqualityComparer
1 [Contract])'方法,以及此方法无法翻译成商店表达。
有什么想法吗?谢谢。
答案 0 :(得分:4)
怎么样;
var contract = dc.Contracts
.Where(c => selectedContracts.Select(x => x.OID).ToList().Contains(c.OID));
答案 1 :(得分:0)
许多人认为无论他们通过linq-to-objects做什么,都可以通过linq-to-entities来完成 - 这是不正确的。普遍的例子是尝试使用.ToString()
,.SubString()
,.Intersect()
等。
要在L2E中交叉实体集,您应该使用.Contains()
方法:
var contract = from c in db.Contracts
where selectedContracts.Contains(c.ContractID)
select c;