You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC:按TaskId在单页获取关联多表数据问题

问题场景与代码现状

我正在开发N层架构的ASP.NET Core MVC项目,数据库包含两张表:

  • TaskList:主键TaskID,字段TaskDetail
  • TaskListComment:主键CommentId,字段CommentDetail、TaskId(关联TaskList的TaskID)

现有Index视图展示TaskList数据,点击TaskID跳转至TaskDetail视图(原Index2)展示对应TaskList详情,现在需要在TaskDetail视图同时展示该TaskID对应的所有TaskListComment数据。但现有代码调用GenericRepository的GetById方法时,会按TaskListComment的主键CommentId查询,而非关联的TaskId,导致无法获取正确的评论数据。

相关代码如下:

GenericRepository.cs

public T GetById(int id)
{
    using var context = new Context();
    return context.Set<T>().Find(id);
}

TaskListCommentManager.cs

public TaskListComment itemGetById(int id)
{
    return _taskListCommentDal.GetById(id);
}

TaskListController.cs

[HttpGet]
public IActionResult TaskDetail(int id)
{
    taskListViewModel.TaskLists = taskListManager.itemGetById(id);
    return View(taskListViewModel);
}
解决方案

1. 扩展GenericRepository,添加条件查询集合的方法

要获取同一TaskId下的所有评论,需要新增支持条件过滤的查询方法:

public IEnumerable<T> GetAllByCondition(Expression<Func<T, bool>> condition)
{
    using var context = new Context();
    return context.Set<T>().Where(condition).ToList();
}

2. 修改TaskListCommentManager,新增按TaskId查评论的方法

替换原有单条查询逻辑,新增查询评论列表的方法:

public IEnumerable<TaskListComment> GetCommentsByTaskId(int taskId)
{
    return _taskListCommentDal.GetAllByCondition(c => c.TaskId == taskId);
}

3. 调整ViewModel,添加评论列表属性

确保ViewModel包含存储评论集合的属性:

public class TaskListViewModel
{
    public TaskList TaskLists { get; set; }
    // 新增评论列表属性
    public IEnumerable<TaskListComment> TaskComments { get; set; }
}

4. 修改Controller逻辑,同时获取任务与评论

在TaskDetail方法中同时查询TaskList详情和对应评论列表,赋值给ViewModel:

[HttpGet]
public IActionResult TaskDetail(int id)
{
    taskListViewModel.TaskLists = taskListManager.itemGetById(id);
    // 获取当前任务对应的所有评论
    taskListViewModel.TaskComments = taskListCommentManager.GetCommentsByTaskId(id);
    return View(taskListViewModel);
}

5. 在TaskDetail视图渲染评论数据

在视图中遍历评论集合展示内容:

<!-- 展示任务详情 -->
<div>
    <h3>任务详情</h3>
    <p>@Model.TaskLists.TaskDetail</p>
</div>

<!-- 展示评论列表 -->
<div>
    <h4>评论</h4>
    @if (Model.TaskComments.Any())
    {
        foreach (var comment in Model.TaskComments)
        {
            <div class="comment-item">
                <p>@comment.CommentDetail</p>
            </div>
        }
    }
    else
    {
        <p>暂无评论</p>
    }
</div>

内容的提问来源于stack exchange,提问作者Gökmen Ada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 08:28:26