LINQ to SQL: Left join on multiple columns

前端 未结 3 982
一生所求
一生所求 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:20

    In your query you didn't do any left join. Try this:

    from p in _db.places
    join v in _db.VoteLogs
    
    //This is how you join by multiple values
    on new { Id = p.Id, UserID = userId } equals new { Id = v.PlaceId, UserID = v.UserID } 
    into jointData
    
    //This is how you actually turn the join into a left-join
    from jointRecord in jointData.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 = jointRecord.Vote 
        /* The row above will fail with a null reference if there is no record due to the left join. Do one of these:
           UserVoted = jointRecord ?.Vote - will give the default behavior for the type of Uservoted
           UserVoted = jointRecord == null ? string.Empty : jointRecord.Vote */
    }
    

提交回复
热议问题