Reputation: 21007
I have two tables. One user table and one table in which results are placed of a certain test.
When a user takes a test his result and his user_id are placed in the results table. When a user never took a test then obviously his user_id won't be in the results table.
I need to get all the users that are NOT in the results table. Is there a way to do this in one query? (Entity Framework)
Getting all the users is easy. But now i need a way to link it to the results table to see which of the users i want in my result set.
(from u in entity.Users
[where not in results table..??]
select u);
Upvotes: 1
Views: 75
Reputation: 25056
Fully working example, using mock objects:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var usersTakenTest = new List<string>() { "Bob", "Jim", "Angel" };
var allUsers = new List<string> { "Bob", "Jim", "Angel", "Mike", "JimBobHouse" };
var users = from user in allUsers
join userTakenTest in usersTakenTest on user equals userTakenTest into tempUsers
from newUsers in tempUsers.DefaultIfEmpty()
where string.IsNullOrEmpty(newUsers)
select user;
foreach (var user in users)
{
Console.WriteLine("This user has not taken their test: " + user);
}
Console.ReadLine();
}
}
}
.DefaultIfEmpty() is what you are after - if it brings back an empty result you have an object in table A that does not show in table B.
Upvotes: 2