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

EF Core中为子记录注入外键:关联父Agreement创建Bundle

解决自动携带AgreementId创建Bundle的方案

核心思路:通过URL传递当前Agreement的Id到Create页面,在Create GET方法中初始化Bundle的外键值,最终提交时自动携带该值完成关联。


步骤1:在Bundle列表页传递AgreementId

首先修改BundlesController的Index方法,将当前AgreementId存入ViewData:

// GET: Bundles
public async Task<IActionResult> Index(int? id)
{
    ViewData["CurrentAgreementId"] = id; // 新增:传递当前AgreementId到视图
    return _context.Bundles != null ?
    View(await _context.Bundles.Where(p => p.AgreementId == id).ToListAsync()) :
                Problem("Entity set 'unidContext.Bundles'  is null.");
}

然后修改Index.cshtml中的「Add Bundle」链接,添加asp-route-agreementId参数:

<a asp-controller="Bundles" asp-action="Create" 
   asp-route-agreementId="@ViewData["CurrentAgreementId"]" 
   class=" btn btn-primary">
    <i class="fa-solid fa-circle-plus"></i> &nbsp; Add Bundle
</a>

步骤2:修改Create GET方法初始化Bundle外键

添加/修改BundlesController的Create GET方法,接收AgreementId并初始化Bundle对象:

// GET: Bundles/Create
public IActionResult Create(int? agreementId)
{
    var bundle = new Bundle();
    if (agreementId.HasValue)
    {
        bundle.AgreementId = agreementId.Value; // 自动设置外键
    }
    return View(bundle);
}

步骤3:优化Create视图的AgreementId字段处理

为避免用户误修改,推荐将AgreementId设为隐藏字段,或只读输入框:

方案A:隐藏字段(用户不可见,推荐)

<div class="form-group">
    <input asp-for="AgreementId" type="hidden" />
</div>

方案B:只读输入框(用户可见但不可修改)

<div class="form-group">
    <label asp-for="AgreementId" class="control-label"></label>
    <input asp-for="AgreementId" class="form-control" readonly />
    <span asp-validation-for="AgreementId" class="text-danger"></span>
</div>

步骤4:完善POST Create方法(可选)

当前POST方法已包含AgreementId绑定,可添加校验并优化重定向逻辑:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,StartUtc,EndUtc,Quantity,AgreementId,BundlePrice")] Bundle bundle)
{
    // 可选:校验AgreementId是否有效
    if (!_context.Agreements.Any(a => a.Id == bundle.AgreementId))
    {
        ModelState.AddModelError("AgreementId", "无效的协议ID");
    }
    
    if (ModelState.IsValid)
    {
        _context.Add(bundle);
        await _context.SaveChangesAsync();
        // 重定向回当前协议的Bundle列表,而非通用列表
        return RedirectToAction(nameof(Index), new { id = bundle.AgreementId });
    }
    return View(bundle);
}

内容的提问来源于stack exchange,提问作者A Cameron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:39:32