Linq to Sql与left join,Lambda不同

时间:2018-05-14 12:01:24

标签: c# sql linq lambda

我试图将下面的查询重写为Linq语句。 查询应该返回一个" User"包含四个属性的对象(Id,FirstName,LastName,Email)。

SELECT DISTINCT Id, FirstName, LastName, Email FROM User
LEFT JOIN Booklet ON Booklet.UserId = User.Id
WHERE Booklet.YearReleased = @YearOfRelease 
ORDER BY LastName ASC

现在我有类似的东西,但是Group by是不正确的,并且它看起来都不是很好的编码...我觉得这可以在一个声明中进行大量优化但我没有这样做。 (演示年' 18')。

List<User> = new List<User>();

List<int?> lstUserIds = db.Booklet.GroupBy(x => x.UserId && x.YearReleased)
                                  .Where(x => x.YearReleased == 18)
                                  .OrderBy(x => x.LastName)
                                  .Select(x => x.UserId)
                                  .ToList();

foreach (int iUserId in lstUserIds )
    lst.Add(db.User.First(x => x.Id == iUserId));

3 个答案:

答案 0 :(得分:1)

Tr this:

List<User> lst = db.User.Include(B => B.Booklet)
                        .Where(B => B.YearReleased == 18)
                        .OrderBy(x => x.LastName)
                        .Distinct()
                        .ToList();

答案 1 :(得分:1)

如果您使用Any(),则不需要与小册子分开,也不需要离开小册子。

var users = db.User
             .Where(u => db.Booklet.Any(b => u.Id == b.UserId && b.YearReleased == 18))
             .OrderBy(u => u.LastName);

答案 2 :(得分:0)

我会使用连接来获得左外连接:

List<int?> lstUserIds = (from b in db.Booklet.Where(x => x.YearReleased == 18)
    join on u in User on b.Id equal u.Id into ids
    from id in ids.DEfaultIfEmpty
    select new { user = u, books = b})
    .OrderBy(x => x.user.LastName)
    .GroupBy(x -> x.user.UserId)
    .Select(x => x.FirstOrDefault())
    .ToList();