我在DB如何通過
- VoucherQuestionCollection
- 後
- PostComment三個表(包含POST表的多個評論) 與秩序和組運行的Linq
表格之間的關係是
VoucherQuestionCollection.discussionid = Post.PostId
and Post.PostId = PostComment.PostId
VoucherQuestionCollection表有一列名爲「WonDate」的列,其中包含日期時間值。我需要的是,我需要獲取從VoucherQuestionCollection表基於以下條件的數據: -
- VoucherQuestionsCollection的WonDate應該是最少的日期(說這即將過期第一個)
- PostComment的評論數也應該是最不重要的。 (這是評論最低的帖子)
那麼,如何在Linq中構建查詢以通過考慮上述條件生成所需的輸出?
這是我到目前爲止所做的,但堅持如何進一步發展。
var voucherQuestionTotalCollection = (from voucherQuestionCollection in this.GetDbSet<Jimble.Model.VoucherQuestionCollection>()
join posts in this.GetDbSet<Jimble.Model.Post>() on voucherQuestionCollection.DiscussionId equals posts.PostId
join comm in this.GetDbSet<Jimble.Model.PostComment>() on posts.PostId equals comm.PostId into gj
from sub in gj.GroupBy(c => c.PostId).Select(g => new { Available = g.Count() }).DefaultIfEmpty()
where voucherQuestionCollection.UserId != userId && voucherQuestionCollection.VoucherWonDate > DateTime.Now.AddDays(-7)
orderby voucherQuestionCollection.VoucherWonDate descending
select new { Id = voucherQuestionCollection .Id,
VoucherWonDate = voucherQuestionCollection.VoucherWonDate,
DiscussionId = voucherQuestionCollection.DiscussionId,
TotCommentCount = sub.Available
}).OrderBy(c=>c.TotCommentCount);
樣品表
VoucherQuestionCollection Post PostComment
Id DiscussionId WonDate Id PostText Id PostId CommentText
1 1 2014-11-21 17:13:00.113 1 FirstPost 1 1 CommentText1
2 2 2014-11-22 17:13:00.113 2 SecondPost 2 1 CommentText2
3 3 2014-11-23 17:13:00.113 3 ThridPost 3 2 CommentText3
4 4 2014-11-24 17:13:00.113 4 FourthPost 4 2 CommentText4
5 2 CommentText5
6 3 CommentText6
這是輸出,我需要 如果表中的狀態是像上面顯示我的預期輸出是VoucherCollectionTable的第三項,因爲它在評論只有一個計數表。 如果PostComment表具有相同的意見,我需要得到的1來自VoucherCollectionTable進入,因爲至少日期爲2014年11月21日17:13:00.113
注意:本VoucherQuestionCollection將有多個條目,我需要根據上述條件僅取6條記錄。
有鬧明白我上面的解釋,只是這是SQL查詢
Select * from VoucherQuestionCollections a
inner join Posts b on a.DiscussionId = b.PostId
Left join (Select PostComments.PostId,COUNT(PostComments.PostId) as tot from PostComments Group by PostComments.PostId)c on b.PostId = c.PostId
order by a.VoucherWonDate,c.tot
如何寫這個相同Linq中
您可以添加您期望的任何樣本輸入和輸出嗎?它很難理解你的數據庫表結構。 – 2014-11-25 09:35:12
@RahulSingh是我的問題,仍然令人困惑?請檢查我編輯的問題。 – 2014-11-25 10:38:27
@JeffMercado你有任何解決方案嗎? – 2014-11-25 10:56:02