Below mentioned query is in SQL Server 2008:
SELECT * FROM Posts p
INNER JOIN Categories c ON p.CategoryId = c.CategoryId
INNER JOIN Users u ON p.UserId = u.UserId
INNER JOIN Tags t ON p.TagId = t.TagId
INNER JOIN Locations l ON p.LocationId = l.LocationId
left JOIN PostImages pm ON p.PostId = pm.PostId
WHERE p.CategoryId = 1 and **pm.PostimageId = (select top 1 postimageid from PostImages where PostImages.PostId=p.postid)**
Now I want to convert the above SQL query into LINQ
My LINQ query:
var objPosts = (from p in _dbcontext.Posts
join us in _dbcontext.Users on p.UserId equals us.UserId
join tag in _dbcontext.Tags on p.TagId equals tag.TagId
join cat in _dbcontext.Categories on p.CategoryId equals cat.CategoryId
join loc in _dbcontext.Locations on p.LocationId equals loc.LocationId
join img in _dbcontext.PostImages on p.PostId equals img.PostId into gj
from postimg in gj.DefaultIfEmpty()
where p.Disabled == false && p.CategoryId == userPost.CategoryId || p.UserId == userPost.UserId || p.TagId == userPost.TagId || p.LocationId == userPost.LocationId
&& postimg.PostImageId == (from pm in _dbcontext.PostImages where pm.PostImageId == p.PostId)
orderby p.PostId descending
select new
{
PostId = p.PostId,
PostTitle = p.Title,
//ImageInfo = postimg.ImagePath,
//ThumbNailInfo = p.ThubNailInfo,
PostShortDescription = p.ShortDescription,
UserId = us.UserId,
UserName = us.Name,
TagId = tag.TagId,
TagTitle = tag.TagTitle,
CategoryId = cat.CategoryId,
CategoryName = cat.CategoryName,
LocationId = loc.LocationId,
LocationName = loc.LocationName
});
I am almost done but I am unable to convert the mentioned SQL query into LINQ.
Thanks.
似乎您只是缺少对内部查询的First()
调用(与SQL查询的top 1
部分相对应):
&& postimg.PostImageId == (from pm in _dbcontext.PostImages where pm.PostId == p.PostId select pm.PostImageId).First()
请像下面这样使用FirstOrDefault:
&& postimg.PostImageId == (from pm in _dbcontext.PostImages where pm.PostImageId == p.PostId).FirstOrDefault()
I know its not relevant answer but it should definitely work. Have you heard about Linqer . If not give it a try.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.