2014-01-17 255 views
0

下文提到的查詢是在SQL Server 2008:轉換SQL Server查詢到LINQ

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。

謝謝。

回答

0

看來,你只是缺少First()呼籲內部查詢(對應於SQL查詢的top 1部分):

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

它給我錯誤:查詢正文必須以select子句或group by子句 – user3124690

+0

@ user3124690結尾,請參閱update – Andrei

0

請使用FirstOrDefault喜歡這裏:

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

我知道它不相關的答案,但它肯定應該工作。你有沒有聽說過Linqer。如果不是試試看。