2
我有2個表稱爲類別和票,我想使用這兩個表已經在我的數據庫中,使我的統計表。MVC5 SQL左加入查詢
我已經成功創建了類別列,但我不知道如何使我的票證發佈列工作。
我的票證發行欄基本上將所有票據分類到各自的類別並對其進行計數。
我需要在HomeController中編寫代碼,以便我可以將兩個表中的CategoryID鏈接在一起,並在About.cshtml中將鏈接顯示在關於頁面上。
HomeController.cs < --Need修改代碼在這裏
public ActionResult About()
{
var data = from category in db.Categories
group category by category.Title into categoryGroup
select new CategoryGroup()
{
Title = categoryGroup.Key,
CategoryCount = categoryGroup.Count() <-- ***This needs to change into Count of Tickets which have the same category ID***
};
return View(data);
}
的ViewModels \ CategoryGroup
public class CategoryGroup
{
public int CategoryID { get; set; }
public int CategoryCount { get; set; }
public string Title { get; set; }
}
About.cshtml
@model IEnumerable<RecreationalServicesTicketingSystem.ViewModels.CategoryGroup>
@{
ViewBag.Title = "Ticket Statistics";
}
<h2>Ticket Category Statistics</h2>
<table>
<tr>
<th>
Category
</th>
<th>
Tickets Issued
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@item.CategoryCount @*Instead of Category Count I want numbers of tickets that have been issued for certain IDs. *@
</td>
</tr>
}
</table>
僅參考
票務類
public enum Priority
{
Low,Med,High
}
public class Ticket
{
public int TicketID { get; set; }
public int CategoryID { get; set; }
public int UserID { get; set; }
public string Issue { get; set; } //A line for our issue like enrollment date in student
public Priority? Priority { get; set; }
public virtual Category Category { get; set; }
public virtual User User { get; set; }
}
範疇類
public class Category
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CategoryID { get; set; }
public string Title { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
嗯,這比我想象的更容易!完美工作!還有一個問題:如果我要創建多個表,是否必須查詢該var數據中的所有數據?或者我可以做另一個名爲var data2並返回View(data2);正確的返回查看(數據); ?? – TykiMikk
@JasonWan - 你只能有一個return語句,並且視圖只有一個模型 - 所以你需要把它放在同一個數據變量中。 –
因此,數據變量是一個空間,您可以查詢一堆數據,如類別標題,票務優先級或用戶ID,然後在About.cshtml中引用它以顯示它? – TykiMikk