将WHERE NOT IN或LEFT JOIN转换为LINQ

时间:2011-12-02 17:09:59

标签: c# linq ef-code-first

我首先使用EF代码设置以下域模型:

public class User
{
    public virtual int Id { get; set; }
    public virtual string Email { get; set; }
    public virtual ICollection<UserProcessed> UsersProcessed { get; set; }
}

public class UserProcessed
{
    public virtual int Id { get; set; }
    public virtual DateTime CreatedAt { get; set; }
    public virtual User user { get; set; }
}

我正在尝试将以下T-SQL查询转换为LINQ,我遇到了一些困难:

SELECT u.Email
FROM Users u LEFT JOIN UsersProcessed up ON u.Id = up.UserId
WHERE up.UserId IS NULL
AND u.CreatedAt BETWEEN '2011-12-01' AND '2011-12-01'

这将返回所有尚未处理的用户(UserPd不存在于UsersProcessed表中)。

IEnumerable<User> users = Database.Set<User>().Where(....).ToList();

1 个答案:

答案 0 :(得分:5)

在生成SQL时,这可能无法转换为完全相同的查询,但它应该可以解决这个问题:

IEnumerable<User> users = Database.Set<User>().Where(u => !u.UserProcessed.Any()).ToList();