2016-03-06 61 views
0

我想從2表中使用Linq的數據,即一個表有FK到第二個表,但沒有必要有數據(表審查可能有每個審查意見(很多) )我想要得到的是:在單個視圖中獲取所有評論,如果有任何評論顯示他們與審查相關Id 試圖使用連接讓我錯誤在我的看法(模型傳遞是錯誤的,我試過每個表格模型),這是我的代碼:linq to sql geting數據從2表

 public ActionResult ttt() 
    { 
     var model = from rev in db.reviews 
        join com in db.Comments 
        on rev.ReviewId equals com.ReviewId into JoineRevCom 
        from com in JoineRevCom.DefaultIfEmpty() 
        select new 
        { 
         rev.ReviewBody, 
         rev.ReviewHeadLine, 
         Comments = com != null ? com.CommentBody : null 
        }; 
     return View(model); 

    } 
@model IEnumerable< SiteMvcPro.Models.Review> 
+0

您的'select new {...}'創建了一個匿名對象集合(不是'Review'對象集合)。你需要用你想要的屬性(例如'ReviewVM')創建一個視圖模型,並使用'選擇新的ReviewVM {....}'(並將視圖中的模型更改爲'model IEnumerable ' –

+0

看左外層加入以下網頁:https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b#content – jdweng

回答

2

一如往常我會寫包含我想顯示,從來沒有像你那樣發送匿名對象到您的視圖中的信息這一觀點視圖模型啓動碼。

讓我們假設你想要顯示一個評論列表,併爲每個評論列出相應的評論。所以你的視圖模型看起來可能沿着這些線路:

public class ReviewViewModel 
{ 
    public int ReviewId { get; set; } 
    public string ReviewBody { get; set; } 
    public string ReviewHeadLine { get; set; } 
    public IList<CommentViewModel> Comments { get; set; } 
} 

public class CommentViewModel 
{ 
    public string CommentBody { get; set; } 
} 

這個定義,你可以執行你的LINQ查詢,提取必要的數據和項目,這個視圖模型:

IEnumerable<ReviewViewModel> viewModel = 
    from review in db.reviews 
    join comment in db.Comments 
    on review.ReviewId equals comment.ReviewId into joinedReviewComment 
    select new ReviewViewModel // <-- Always project to a view model and never to an anonymous object 
    { 
     review.ReviewBody, 
     review.ReviewHeadLine, 
     Comments = joinedReviewComment.Select(c => new CommentViewModel 
     { 
      CommentBody = c.CommentBody, 
     }).ToList(), 
    }; 

return View(viewModel.ToList()); // <-- Always pass a view model to your view 

而現在所有這左邊是顯示在你的強類型查看此信息:

@model IList<ReviewViewModel> 

<table> 
    <thead> 
     <tr> 
      <th>Review id</th> 
      <th>Review body</th> 
      <th>Review headline</th> 
      <th>Review comments</th> 
     </tr> 
    </thead> 
    <tbody> 
     @for (var i = 0; i < Model.Count; i++) 
     { 
      <tr> 
       <td>@Html.DisplayFor(x => x[i].ReviewId)</td> 
       <td>@Html.DisplayFor(x => x[i].ReviewBody)</td> 
       <td>@Html.DisplayFor(x => x[i].ReviewHeadLine)</td> 
       <td> 
        @for (var j = 0; j < Model[i].Comments.Count; j++) 
        { 
         <div> 
          @Html.DisplayFor(x => x[i].Comments[j].CommentBody) 
         </div> 
        } 
       </td> 
      </tr> 
     } 
    </tbody> 
</table> 

話雖如此突出的是一回事,但過濾你的數據是另一回事。假設您有數百萬條評論,每條評論都有數百萬條評論。進行上述查詢將簡單地使您的服務器停機。因此,在設計應用程序和視圖時應考慮這一點。不要猶豫,使用Where,Skip和Take操作符將結果集過濾爲一組有意義的數據集合,這些數據足夠合理,可以在單個視圖中顯示。

+0

謝謝Darin Dimitrov,explant! – Danny