Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 
like image 949
Daybreaker Avatar asked Feb 13 '14 22:02

Daybreaker


People also ask

How do you select all records from one table that do not exist in another table Linq?

Users select e). ToList(); var result2 = (from e in db.Fi select e). ToList(); List<string> listString = (from e in result1 where !( from m in result2 select m.

How do I select data from one table is not in another table?

We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.

How do you check if data in one table exists in another table?

The SQL EXISTS Operator The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.


1 Answers

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.

like image 90
Timothy Walters Avatar answered Oct 14 '22 02:10

Timothy Walters