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

ASP.NET中CRUD开发:实现父实体与子实体关联查询

实现ParentDb与ChildDb的关联及数据查询显示

首先得完善实体类的关联关系,一对多场景下,子实体需要添加外键字段指向父实体,同时配置导航属性:

public class ParentDb
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    // 导航属性:一个父实体对应多个子实体,初始化集合避免空引用
    public List<ChildDb> Children { get; set; } = new List<ChildDb>();
}

public class ChildDb
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // 外键字段:关联父实体的Id
    public int ParentId { get; set; }
    // 导航属性:子实体对应的父实体
    public ParentDb Parent { get; set; }
}

接下来在DbContext里明确配置这对一对多关系,用Fluent API更清晰:

public class YourDbContext : DbContext
{
    public DbSet<ParentDb> Parents { get; set; }
    public DbSet<ChildDb> Children { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 配置ParentDb与ChildDb的一对多关联
        modelBuilder.Entity<ParentDb>()
            .HasMany(p => p.Children) // 父实体有多个子实体
            .WithOne(c => c.Parent)   // 每个子实体对应一个父实体
            .HasForeignKey(c => c.ParentId) // 子实体的外键字段是ParentId
            .OnDelete(DeleteBehavior.Cascade); // 可选:删除父实体时自动删除关联的子实体,根据业务调整
    }
}

添加ChildDb数据时关联父实体

在控制器的添加方法里,要给ChildDb指定有效的ParentId(确保对应的父实体存在),示例代码:

[HttpPost]
public IActionResult AddChild(ChildDb child)
{
    if (ModelState.IsValid)
    {
        // 先校验父实体是否存在
        if (_context.Parents.Any(p => p.Id == child.ParentId))
        {
            _context.Children.Add(child);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
        ModelState.AddModelError("ParentId", "指定的父实体不存在");
    }
    return View(child);
}

查询父实体时加载子实体列表

要查询带子实体的父列表,必须用Include方法显式加载关联数据(避免延迟加载可能导致的问题),控制器代码:

[HttpGet]
public IActionResult Index()
{
    // 使用Include一次性加载父实体及其关联的子实体
    var parentsWithChildren = _context.Parents.Include(p => p.Children).ToList();
    return View(parentsWithChildren);
}

视图中展示数据

在Index视图里,直接遍历父实体和对应的子实体即可:

@model List<ParentDb>

@foreach (var parent in Model)
{
    <div class="parent-item">
        <h3>@parent.Title</h3>
        <p>@parent.Description</p>
        <h4>关联子实体:</h4>
        <ul>
            @foreach (var child in parent.Children)
            {
                <li>@child.FirstName @child.LastName</li>
            }
        </ul>
    </div>
}

内容的提问来源于stack exchange,提问作者C.NCB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:53:26