Linq To EF:如何使用非原始类型进行过滤 [英] 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.Name == p.Name));
上述代码生成NotSupportedException,因为Linq to Entities不支持引用非标量变量(人
)。
The above code generates a NotSupportedException, because Linq to Entities does not support referencing non-scalar variables(Person
).
我该如何解决?谢谢!
//编辑:我正在寻找personEntities的人,他们与personOfInterest列表中的任何人具有相同的名称和相同的工作。例如,我试图在我的人物中找到任何一个名叫鲍勃或程序员的警察的名字约翰。_
我得到的错误描述在这里。(22.2)
//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()));
创建类:
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 如果第一个不是一个选项,您可以沿着一行(概念)进行连接:
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();
我不知道你的课程内部,所以你必须调整示例为了适应您的对象结构。
已编辑
我修改了上述示例以反映您编辑过的描述:
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是一个自定义集合类型,或者这是一个表/复杂类型在你的EF模型?
PersonEntities in your code, is that a custom collection type or is this a table/complex type in your EF model?
这篇关于Linq To EF:如何使用非原始类型进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!