如何通过Linq从同一个表中连接多个列?
例如:我已经有了......
join c in db.table2 on table2.ID equals table1.ID
Run Code Online (Sandbox Code Playgroud)
我需要添加这个......
join d in db.table2 on table2.Country equals table1.Country
Run Code Online (Sandbox Code Playgroud) 首先,我搜索了google/SO,检查了一些示例,但我没有设法编写正确的linq表达式:
这是我的工作SQL查询的样子:
select *
from Places p
left join VoteLog v
on p.Id = v.PlaceId
and v.UserId = '076a11b9-6b14-4230-99fe-28aab078cefb' --demo userid
Run Code Online (Sandbox Code Playgroud)
这是我对linq的尝试:
public IQueryable<Place> GetAllPublic(string userId)
{
var result = (from p in _db.Places
join v in _db.VoteLogs
on p.Id equals v.PlaceId // This works but doesn't fully reproduce my SQL query
// on new { p.Id, userId} equals new {v.PlaceId, v.UserId} -> Not ok
where p.Public == 1
select new
{
Id = p.Id,
UserId = p.UserId,
X = …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Linq to SQL作为Lambda表达式在2列上进行内部联接。普通查询如下所示。
SELECT * FROM participants
LEFT OUTER JOIN prereg_participants ON prereg_participants.barcode = participants.barcode
AND participants.event_id = prereg_participants.event_id
WHERE (participants.event_id = 123)
Run Code Online (Sandbox Code Playgroud)
我成功地在左列上使用以下代码进行了联接。
var dnrs = context.participants.GroupJoin(
context.prereg_participants,
x => x.barcode,
y => y.barcode,
(x, y) => new { deelnr = x, vi = y })
.SelectMany(
x => x.vi.DefaultIfEmpty(),
(x, y) => new { deelnr = x, vi = y })
.Where(x => x.deelnr.deelnr.event_id == 123)
.ToList();
Run Code Online (Sandbox Code Playgroud)
问题在于,使用上述Lambda时,我得到了太多结果,因为它缺少AND participants.event_id = prereg_participants.event_id零件。但是,无论我怎么努力,我都没有得到正确数量的参与者。
我查看了以下现有问题,但是在编写正确的lambda时没有一个解决了我的问题。而且大多数解决方案都是lambda格式的nog或不是多列上的Left外部联接。