Using LINQ intersect function with a non-primitive type
I'm using ENtity Framework with Code First. I have a list of objects that are being passed to a function, which will use the Intersect function from the DatabaseContext and pass the objects. It's not working. Here's the code:
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();
}
I created a ContractComparer class which implements 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
}
The error i get is:
LINQ to Entities does not recognize the method 'System.Linq.IQueryable1[Contract] Intersect[Contract](System.Linq.IQueryable
1[Contract], System.Collections.Generic.IEnumerable1[Contract], System.Collections.Generic.IEqualityComparer
1[Contract])' method, and this method cannot be translated into a store expression.
Any ideas? Thanks.
How about;
var contract = dc.Contracts
.Where(c => selectedContracts.Select(x => x.OID).ToList().Contains(c.OID));
Many poeple think that whatever they can do by linq-to-objects, can be done by linq-to-entities too - That's not correct. Prevalent examples are trying to use .ToString()
, .SubString()
, .Intersect()
, etc.
To intersecting entity sets in L2E, you should use .Contains()
method:
var contract = from c in db.Contracts
where selectedContracts.Contains(c.ContractID)
select c;
精彩评论