我有问题:
1)如何将此select转换为LINQ?
Select i.ID, i.Impression,
(Select COUNT(ImpressionsId)
from DiaryImpressions
where DiaryPostsId = '2' AND ImpressionsId = i.ID) as Num from Impressions i
2)我必须在循环中运行此查询,我可以替换真实帖子ID的硬编码值2
。但是我怎么能用C#和MVC3做这个呢?有人可以给我任何关于它如何在foreach循环中工作的例子,我怎么能在视图中显示这个值?
Thanx很多=)
答案 0 :(得分:1)
您是否已经设置了数据库上下文/存储库以与MVC项目中的数据库进行通信?下面我假设你有一个名为dbContext的数据库上下文。
注意:如果您没有使用Razor,请将“@”替换为“<%”,并使用“%>”关闭
您可以将项目放在ViewBag中,也可以放在模型中(我更喜欢模型),如下所示。我不确定你想对这些计数做什么,所以我把它们放在一个列表中。您需要一个课程来展示您的展示信息,我已将其添加到下方;
型号代码:
public class MyModel
{
public class ImpressionInfo //just used to store your results sub class of the model
{
public ImpressionInfo(id, impression, diaryImpressionCount)
{
Id = id;
Impression = impression;
DiaryImpressionCount = diaryImpressionCount
}
public int Id { get; set; }
public int Impression { get; set; } //is this an int? you didn't say
public int DiaryImpressionCount { get; set; }
}
public MyModel()
{
var impressionInfo = new List<ImpressionInfo>()
foreach (var di in dbContext.DiaryImpressions)
{
ImpressionInfos.Add(new ImpressionInfo(
di.Id,
di.Impression,
dbContext.DiaryPosts
.Count(dp => dp.ImpressionsId == di.ID));
}
}
public List<ImpressionInfo> ImpressionInfos { get; set; }
然后在视图中
查看代码:
@model MyModel
@if(Model.ImpressionInfos.Count > 0)
{
<table>
<tr>
<td>Impression</td>
<td>Count</td>
</tr>
foreach (var i in Model.ImpressionInfos)
{
<tr>
<td>@i.Impression</td>
<td>@i.DiaryImpressionCount</td>
</tr>
}
}
else
{
<p>No Impression infos</p>
}
希望这有帮助。