c# - MVC5 SQL 左连接查询

标签 c# mysql asp.net-mvc entity-framework

我有 2 个名为 Category 和 Ticket 的表,我想使用数据库中已有的这 2 个表来制作我的统计表。

我已成功创建“类别”列,但我不知道如何使“已发行的门票”列发挥作用。

“我的门票已发行”列基本上是将所有门票分类到各自的类别中并进行计数。

我需要在 HomeController 中进行编码帮助,以便我可以将两个表中的 CategoryID 链接在一起,并在 About.cshtml 中进行一些链接以在“关于”页面上显示该表。

enter image description here 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; }
    }

关于.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()
           };

关于c# - MVC5 SQL 左连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35635328/

相关文章:

c# - 在 C# 中使用 RazorViewEngine 的转换功能

c# - AWS Systems Manager 参数存储 : Lambda function hangs

c# - 将单选按钮列表添加到 ascx

php - 更新 2 个字段相等的字段

javascript - 重构 JS 对象以适应绑定(bind) MVC 模型

asp.net - 使用 MySql 和 MVC 3 上的成员(member)资格向注册表单添加更多字段

c# - 如何检查 MVC 应用程序的应用程序空闲状态

c# - 从 FormView 中的 TextBox 获取日期时间值

mysql - SQL连接多行

c# - UPDATE (MySQL) 无法与 C# 和 ASP.NET 结合使用