仅当其他用户未出现在其他表中时,才获取所有用户
本文关键字:用户 其他 获取 | 更新日期: 2023-09-27 18:36:30
我有两个表。一个用户表和一个放置特定测试结果的表。
当用户进行测试时,他的结果和user_id将放在结果表中。当用户从未参加过测试时,显然他的user_id不会出现在结果表中。
我需要获取不在结果表中的所有用户。有没有办法在一个查询中做到这一点?(实体框架)
获取所有用户很容易。但是现在我需要一种方法来将其链接到结果表,以查看我想要的结果集中的哪些用户。
(from u in entity.Users
[where not in results table..??]
select u);
使用模拟对象的完整工作示例:
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() 是你所追求的 - 如果它带回一个空结果,你在表 A 中有一个对象没有显示在表 B 中。