将SQL Server Query转换为Linq

时间:2014-01-17 11:06:35

标签: c# linq sql-server-2008

下面提到的查询是在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)**

现在我想将上面的SQL查询转换为LINQ

我的LINQ查询:

   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
                            });

我差不多完成但我无法将提到的SQL查询转换为LINQ。

感谢。

3 个答案:

答案 0 :(得分:0)

您似乎错过了对内部查询的First()调用(对应于SQL查询的top 1部分):

&& postimg.PostImageId == (from pm in _dbcontext.PostImages where pm.PostId == p.PostId select pm.PostImageId).First()

答案 1 :(得分:0)

请像这里一样使用FirstOrDefault:

&& postimg.PostImageId == (from pm in _dbcontext.PostImages where pm.PostImageId == p.PostId).FirstOrDefault()

答案 2 :(得分:0)

我知道它不是相关的答案,但绝对应该有效。你听说过Linqer吗?如果不试一试。