我使用的是代码优先的ENtity框架。我有一个传递给函数的对象列表,该函数将使用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();
}
我创建了一个ContractComparer类,它实现了IEqualityComparer:
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.Iueryable 1[Contract] Intersect[Contract](System.Linq.IQueryable
1[Contact],System.Collections.Generic.IEnumerable 1[Contract], System.Collections.Generic.IEqualityComparer
1[Contract])",并且此方法无法转换为存储表达式。
有什么想法吗?谢谢
怎么样;
var contract = dc.Contracts
.Where(c => selectedContracts.Select(x => x.OID).ToList().Contains(c.OID));
许多人认为linq可以对对象做任何事情,linq也可以对实体做任何事情——这是不正确的。常见的例子是尝试使用.ToString()
、.SubString()
、.Intersect()
等。
要在L2E中相交实体集,应使用.Contains()
方法:
var contract = from c in db.Contracts
where selectedContracts.Contains(c.ContractID)
select c;