Select records that does not exist in another table in Entity Framework

c# entity-framework

Question

I have two tables - "Customer" table and "Blacklist" customer table. When I blacklist a customer, I put the customerid as a foreign key to Blacklist table.

What I want is to get CusId and Name that are not in the BlackList Table.

How can I code this Entity Framework C#?

Customer
---------
(CusId,Name,Telephone,Email)

Blacklist
---------
(CusId)
1
21
3/8/2018 3:11:02 AM

Accepted Answer

What you want is something like the following:

db.Customers
    .Where(c => !db.Blacklists
        .Select(b => b.CusId)
        .Contains(c.CusId)
    );

EF will happily turn that into a sub-query that will run quite well.

This pattern works for static lists (creates an IN(a, b, c) expression) as well as other tables. You can use it to check for being in the list or not in the list.

If you want to test it and see the SQL it generates, I strongly recommend LINQPad (it is free). That's what I use to test out little ideas in LINQ all the time.

48
2/13/2014 10:38:38 PM

Popular Answer

How about something like this:

var subselect = (from b in BlackList select b.CusId).ToList();

var result = from c in Customer where !subselect.Contains(c.CusId) select c;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow