linq to sql geting数据从2表
问题描述:
我想从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>
答
一如往常我会写包含我想显示,从来没有像你那样发送匿名对象到您的视图中的信息这一观点视图模型启动码。
让我们假设你想要显示一个评论列表,并为每个评论列出相应的评论。所以你的视图模型看起来可能沿着这些线路:
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
您的'select new {...}'创建了一个匿名对象集合(不是'Review'对象集合)。你需要用你想要的属性(例如'ReviewVM')创建一个视图模型,并使用'选择新的ReviewVM {....}'(并将视图中的模型更改为'model IEnumerable' –
看左外层加入以下网页:https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b#content – jdweng