LINQ to SQL: Left join on multiple columns

前端 未结 3 946
一生所求
一生所求 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;
    
    0 讨论(0)
  • 2021-01-05 01:15

    If your problem is assigning keywords to those multiple join conditions:

    // on new { p.Id, userId} equals new {v.PlaceId, v.UserId}
    

    try with

    on new { a = p.Id, b = userId} equals new { a = v.PlaceId, b = v.UserId}
    
    0 讨论(0)
  • 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 */
    }
    
    0 讨论(0)
提交回复
热议问题