Linq To EF:如何使用非原始类型进行过滤
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 不支持引用非标量变量 (Person
)。
我该如何解决这个问题?谢谢!
//编辑:我试图从 personEntities 中查找人员,他们与 personOfInterest 列表中的任何人具有相同的姓名和相同的工作。例如,我试图在我的实体中找到一个名为 Bob 的警察或名为 John 的程序员。
我收到的错误在此处中进行了描述。(22.2)
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));
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,两个集合应该包含相同类型的对象。
然后你可以执行以下操作:
创建类:
OR如果第一个不是一个选项,你可以按照以下方式进行连接(概念上):
我不知道内部情况您的类,因此您必须调整示例以适应您的对象结构。
编辑:
我修改了上面的示例以反映您编辑的描述:
代码中的 PersonEntities,是自定义集合类型还是 EF 模型中的表/复杂类型?
First of all both collections should contain objects of the same type.
Then you could do the following:
create the class:
OR if the first is not an option, you could do a join something along the lines(in concept):
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:
PersonEntities in your code, is that a custom collection type or is this a table/complex type in your EF model?
最好比较 ID 而不是对象。这样效率会高很多。问题是 EntityFramework 不知道如何将 obj1 == obj2 转换为 SQL。
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.