Linq To EF : How to filter using Non-Primitive types
public class Person
{
public int ID { get; set; }
public int Job { get; set; }
public string Name { get; set; }
}
List<Person> personsOfInterest = GetPersonsOfInterest();
PersonEntities personEntities = new PersonEntities();
var filteredPersons = personEntities.Where(p => personsOfInterest.Any(poi => poi.Job == p.Job && poi.开发者_如何学GoName == p.Name));
The above code generates a NotSupportedException, because Linq to Entities does not support referencing non-scalar variables(Person
).
how can I resolve this? thanks!
//edit: I am trying to find persons from personEntities, who has same name and same job with anyone in the personOfInterest list. for example, I am trying to find anyone in my personEntities who is a Policeman named Bob or Programmer named John.
the error I'm getting is described in here.(22.2)First of all both collections should contain objects of the same type.
Then you could do the following:
var filteredPerosns = personEntities
.Where(p => personsOfInterest.Contains(p, new MyPersonComparer()));
create the class:
class MyPersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Job == y.Job && x.Name == y.Name;
}
public int GetHashCode(Person obj)
{
return obj.PersonID; //Just for example...
}
}
OR if the first is not an option, you could do a join something along the lines(in concept):
List<int?> listA = new List<int?>() {1, 2, 3, 4, 5, 6, 7};
List<int?> listB = new List<int?>() {5};
bool result = (from a in listA
join b in listB on a equals b
select a).Any();
I do not know the insides of your classes, so you will have to adjust the examples to fit your object structure.
EDITED: I have modified the above example to reflect your edited description:
List<Person> personsOfInterest = GetPersonsOfInterest();
var filteredPersons = (from a in personEntities
join b in personsOfInterest on new{a.Name, a.Job} equals new {b.Name, b.Job}
select a).ToList();
PersonEntities in your code, is that a custom collection type or is this a table/complex type in your EF model?
It would best to compare the IDs rather than the objects. This will be much more efficient. The problem is EntityFramework does not how to translate obj1 == obj2 into SQL.
精彩评论