Linq To EF : How to filter using Non-Primitive types

ぐ巨炮叔叔 提交于 2019-12-21 20:37:06

问题


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)


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/5729202/linq-to-ef-how-to-filter-using-non-primitive-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!