【发布时间】:2011-07-27 17:13:28
【问题描述】:
我有一个查询,我需要在其中获取帖子 + 它拥有的每个标签。但是由于标签在单独的表格中,这让我感到很困难,原因有两个。我不确定我什至需要传递两个值,也许我可以以不同的方式做到这一点。
请注意,模型是使用 LINQ to SQL 类自动创建的。
数据库
代码
public ActionResult Edit(int id)
{
// Get post from DB
var post = (from p in _db.Posts
where p.ID == id
select p).Single();
// Get PostTags from DB
var postTag = (from pt in _db.PostTags
where pt.PostID == id
select pt);
// Now looping through PostTags in order to find all tag names associated with the post
string tagList = string.Empty;
foreach (var pt in postTag)
{
var tag = (from t in _db.Tags
where t.ID == pt.TagID
select t).Single();
tagList += tag.Name + " ";
}
return Content(tagList); // This works as intended, outputs all tags for current post
return View(); // How can I return post itself + tagList ?
}
问题
-
如您所见,我想将
post传递给我的视图,这是有道理的,但我还需要以某种方式传递包含标签的tagList字符串。我该怎么做? -
我认为我的查询不好。我没有使用 SQL/LINQ 的经验,所以这是我唯一想到的。也许我可以更“聪明”地做同样的事情?
好的,谢谢你的回答。 ViewBag 和创建 BlogViewModel 都很好。我想我会选择 BlogViewModel 。但是我的第二个问题仍然存在。
【问题讨论】:
标签: c# asp.net linq linq-to-sql asp.net-mvc-3