我正在学习ASP.net MVC 5,我有一个复杂的查询,我无法在我的控制器中找到它。我需要显示即将到来的里程碑列表,并显示每个里程碑所代表的广告系列所花费的总金额。这些广告系列位于一个表格中,其中一个里程碑位于另一个表格中,服务位于另一个表格中,订单位于另一个
里程碑,广告系列和服务都受CampaignId的约束。订单通过ServiceId绑定到Services表。我首先使用代码和实体框架,但我无法弄清楚如何编写查询来汇编列表以发送到视图。
这是视图
@model IEnumerable
@{
ViewBag.Title = "LookUpMilestones";
Layout = "~/Views/Shared/_LayoutAdminDashboard.cshtml";
}
<div id="adminDash" class="col-md-8 col-xs-10 adminDash light-grey">
<p class="lead text-uppercase">More Upcoming Milestones</p>
<table class="table table-bordered table-condensed">
<thead>
<tr class="active">
<td>Id</td>
<td>Next Milestones</td>
<td>Pledges $ In</td>
<td>Milestone $</td>
<td>Admin</td>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.CampaignId)</td>
<td>@Html.DisplayFor(modelItem => item.TermEndDate)</td>
<td>pledges$</td>
<td>@Html.DisplayFor(modelItem => item.TargetAmount)</td>
<td>
@Html.ActionLink("Details", "../CampaignsFSC/MyDetails/", new { id = item.CampaignId })
</td>
</tr>
}
</tbody>
</table>
</div>
我需要帮助编写我传递给视图的查询以循环并填写字段。除了每个里程碑的总金额之外,我可以得到所有这些,因为该金额存储在Orders表中,但没有直接路径。
[dbo].[MilestoneDetails] (
[id] INT IDENTITY (1, 1) NOT NULL,
[MilestoneId] INT NOT NULL,
[CampaignId] INT NOT NULL,
[UserId] NVARCHAR (MAX) NULL
[dbo].[Order] (
[OrderId] INT IDENTITY (1, 1) NOT NULL,
[UserId] NVARCHAR (128) NOT NULL,
[ServiceId] INT NOT NULL,
[PaymentProfileId] INT NOT NULL,
[OrderDate] DATETIME NOT NULL,
[Amount] REAL NOT NULL
[dbo].[Service] (
[ServiceId] INT IDENTITY (1, 1) NOT NULL,
[CampaignId] INT NOT NULL,
[Cost] DECIMAL (19, 4) NOT NULL,
[Description] NVARCHAR (500) NOT NULL,
[DeliveryDate] DATETIME NOT NULL,
[DeliveryDesc] NVARCHAR (500) NOT NULL,
[MaxQuantity] INT NULL,
[ApprovedDate] DATETIME NULL,
[DisplayOrder] NVARCHAR (MAX) NULL,
[Status] INT NULL
所以这是我尝试将它们全部放在控制器中:
public ActionResult LookUpMilestone()
{
if (ModelState.IsValid)
{
var Milestones = (from m in db.MilestoneDetails
orderby m.TermEndDate ascending
where m.TermEndDate >= System.DateTime.Now
select new {
m.CampaignId,
totalOrders = (from serv in db.Services
on m.CampaignId equals serv.CampaignId
join ord in db.Orders on serv.ServiceId equals
ord.ServiceId).Sum(ord => ord.Amount))}
).Distinct();
return View("LookUpMilestones", Milestones);
答案 0 :(得分:0)
是的,你正走在正确的轨道上。你似乎只是有一些语法问题
select new {
m.CampaignId,
totalOrders = (from serv in db.Services
join ord in db.Orders on serv.ServiceId equals ord.ServiceId
where m.CampaignId == serv.CampaignId
&& ord.UserId == m.UserId //this line might not be correct depending on what UserId is used for
select ord
).Sum(ord => ord.Amount)
}
哦,在您的查询中,只是为了优化,在orderby子句之前放置where子句以减少内存占用
我没有在您的数据库架构中看到TermEndDate或TargetAmount,或者我帮助填写这些属性