LINQ to SQL: Left join on multiple columns

前端 未结 3 967
一生所求
一生所求 2021-01-05 00:57

First of all, I have searched google/SO, checked some examples, but I didn\'t manage to write the proper linq expression:

This is how my working sql query lo

3条回答
  •  自闭症患者
    2021-01-05 01:13

    You have to use .DefaultIfEmpty() to perform a left join. Then you need to decide what to do in case the right table produces null. You can use a ternary operator ( ? : ) for that.

    var result = 
        (from p in _db.Places
        join v in _db.VoteLogs
        on new { p.Id, userId } equals new { v.PlaceId, v.UserId } into LEFTJOIN
        from result in LEFTJOIN.DefaultIfEmpty()
        where p.Public == 1
        select new
        {
            Id = p.Id,
            UserId = p.UserId,
            X = p.X,
            Y = p.Y,
            Titlu = p.Titlu,
            Descriere = p.Descriere,
            Public = p.Public,
            Votes = p.Votes,
            DateCreated = p.DateCreated,
            DateOccured = p.DateOccured,
            UserVoted = result == null ? null /* replace with your value */ : x.Vote
        }).AsQueryable();
    
    return result;
    

提交回复
热议问题