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

ASP.NET Core 1对多表关联:如何加载国家及关联城市至详情页

嘿,我来帮你搞定这个问题!在ASP.NET Core里实现点击国家详情后展示其关联城市的需求,核心是利用EF Core的关联数据加载能力,咱们一步步来操作:

1. 先完善实体类的导航属性

你当前的Country实体里缺少对应下属城市的反向导航属性,EF Core需要这个属性来建立完整的一对多关联关系,所以先给Country类补上:

public class Country 
{ 
    [Key] 
    public int Id { get; set; } 
    [Required] 
    public string CountryName{ get; set; } 
    [Required] 
    public string Continent{ get; set; } 
    [Required] 
    public string Capital{ get; set; } 
    [Required] 
    public int NumberOfPeople{ get; set; }

    // 新增:关联下属城市的导航属性,初始化空集合避免空引用异常
    public ICollection<City> Cities { get; set; } = new List<City>();
}
2. 在控制器中加载关联数据并传递到视图

假设你有一个CountryController,在它的Details方法里,我们用EF Core的Include方法来预先加载国家对应的所有城市数据,这样就能一次性把国家和关联城市都查询出来,避免后续的延迟加载性能问题:

public async Task<IActionResult> Details(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    // 关键:使用Include(c => c.Cities)加载关联的城市数据
    var country = await _context.Countries
        .Include(c => c.Cities)
        .FirstOrDefaultAsync(m => m.Id == id);

    if (country == null)
    {
        return NotFound();
    }

    // 将包含完整关联数据的Country模型传递给视图
    return View(country);
}

小细节补充:如果你确定传入的id一定对应数据库中的有效国家(比如从列表页跳转过来,id都是合法的),可以用SingleOrDefaultAsync替代FirstOrDefaultAsync,它会确保只返回一条匹配数据,更符合主键查询的场景。

3. 在Details视图中展示数据

接下来在Details.cshtml视图里,先展示国家的基础信息,再遍历关联的城市列表:

@model YourProjectNamespace.Models.Country

<h1>国家详情</h1>

<div>
    <h4>@Model.CountryName</h4>
    <hr />
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Continent)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Continent)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Capital)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Capital)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.NumberOfPeople)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.NumberOfPeople)
        </dd>
    </dl>
</div>

<!-- 展示下属城市列表 -->
<div>
    <h5>下属城市</h5>
    <table class="table">
        <thead>
            <tr>
                <th>城市名称</th>
                <th>所属区域</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var city in Model.Cities)
            {
                <tr>
                    <td>@city.CityName</td>
                    <td>@city.Region</td>
                </tr>
            }
        </tbody>
    </table>
</div>

<div>
    <a asp-action="Index">返回列表</a>
</div>

这样操作后,当你从国家列表页点击详情按钮,就能看到该国家的完整信息以及它下属的所有城市啦!

内容的提问来源于stack exchange,提问作者Adin Sijamija

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:49:06