簡體   English   中英

MVC5 SQL左聯接查詢

[英]MVC5 SQL LEFT JOIN QUERY

我有2個名為Category和Ticket的表,我想使用數據庫中已經存在的這2個表來制作統計表。

我已經成功地創建了“類別”列,但是我不知道如何使“已發行的票證”列起作用。

我的已發行票證基本上將所有票證歸為各自的類別並進行計數。

我需要在HomeController中進行編碼的幫助,因此我可以將兩個表中的兩個CategoryID以及一個About.cshtml中的鏈接在一起,以在About頁面上顯示該表。

在此處輸入圖片說明 HomeController.cs <-需要在此處修改代碼

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 data = from category in db.Categories
           select new CategoryGroup()
           {
               CategoryID = category.CategoryID,
               Title = category.Title,
               CategoryCount = category.Tickets.Count()
           };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM