Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Not In" in Entity Framework

I have the following Entity

public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and have a list List<Person> badGuys

what I want to do is select from all persons except those in badGuys List

My Code

context.Persons
    .where(p => !badGuys.Contain(p))
    .ToList()

but I get an error

Only primitive types or enumeration types are supported in this context.

How to fix this?

like image 738
Mohamed Badr Avatar asked Nov 12 '15 09:11

Mohamed Badr


2 Answers

You can use the clause ALL with the distinct(!=)

var badBoys= from P in context.Persons
         where badGuys.All(a => a.PersonId!= P.PersonId)
         select P;
like image 146
Yaina Villafañes Avatar answered Sep 23 '22 10:09

Yaina Villafañes


You could make an array containing the ids of the bad guys and filter out those ids (which are of a primitive type, so it should work):

var badGuyIds = badGuys.Select(x => x.PersonId).ToArray();

context.Persons
    .Where(p => !badGuyIds.Contain(p.PersonId))
    .ToList();
like image 21
Cristian Lupascu Avatar answered Sep 25 '22 10:09

Cristian Lupascu