gpt4 book ai didi

c# - LINQ 到 SQL : Left join on multiple columns

转载 作者:太空狗 更新时间:2023-10-29 22:25:39 25 4
gpt4 key购买 nike

首先,我搜索了 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

这是我对 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 = p.X,
Y = p.Y,
Titlu = p.Titlu,
Descriere = p.Descriere,
Public = p.Public,
Votes = p.Votes,
DateCreated = p.DateCreated,
DateOccured = p.DateOccured,
UserVoted = v.Vote
})
.ToList()
.Select(x => new Place()
{
Id = x.Id,
UserId = x.UserId,
X = x.X,
Y = x.Y,
Titlu = x.Titlu,
Descriere = x.Descriere,
Public = x.Public,
Votes = x.Votes,
DateCreated = x.DateCreated,
DateOccured = x.DateOccured,
UserVoted = x.UserVoted
}).AsQueryable();

最佳答案

在您的查询中您没有执行任何左连接。试试这个:

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 */
}

关于c# - LINQ 到 SQL : Left join on multiple columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38431739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com