Linq加入:无法加入2个基于2个ID的列表

时间:2014-03-25 04:26:51

标签: c# sql linq join

我有2个表AtdDailyAttendanceAcdAdmissionSessionDetails。我想基于2个ID从linq加入这两个表,这意味着在Sql中这个连接看起来像

SELECT a.Id, a.DateId,  
    a.StudentLedgerId, a.AttendanceTypeId,   
    a.SchoolId, a.UserId, a.SessionId, 
    d.ClassId,d.MediumId,    
    d.StreamId, d.ShiftId,  
    d.SectionId   
FROM AtdDailyAttendance a INNER JOIN  AcdAdmissionSessionDetail d
    ON a.StudentLedgerId = d.StudentLedgerId AND  a.SessionId = d.SessionId

但在LINQ中,我无法做到这一点。我试过这种方式

var query =
    from a in dbCOntext.AtdDailyAttendances
    join b in dbCOntext.AcdAdmissionSessionDetails
    on a.StudentLedgerId equals b.StudentLedgerId
    // on a.SessionId equlas b.SessionId
    select new
    {
        a.AtdSetedDatesForAttendance,
        a.DateId,
        a.StudentLedgerId,
        a.SchoolId,
        a.UserId,
        a.SessionId,
        b.ClassId,
        b.SectionId,
        b.MediumId,
        b.StreamId
    }

var liResult = query.ToList();

此处我无法在SessionId之间执行联接。

2 个答案:

答案 0 :(得分:2)

我认为您正在寻找:

var liResult = (from a in dbCOntext.AtdDailyAttendances
  join b in dbCOntext.AcdAdmissionSessionDetails
  on new { a.StudentLedgerId, a.SessionId } 
     equals new { b.StudentLedgerId, b.SessionId}

答案 1 :(得分:-1)

看看这是否有效:

 dbContext.AtdDailyAttendances.Join(dbContext.AcAdmissionSessionDetails, m => m.StudentLedgerId,      n => n.StudentLedgerId, (m, n) => new{ 
                                m.AcdAdmissionSessionDetails,
                                m.DateId,
                                m.StudentLedgerId,
                                m.SchoolId,
                                m.UserId,
                                AttendanceSessionId = n.SessionId,
                                AdmissionSessionId = m.SessionId,
                                n.ClassId,
                                n.SectionId,
                                n.MediumId,
                                n.StreamId

  }).Where(n => n.AttendanceSessionId == n.AdmissionSessionId).ToList();