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> 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
相关产品推荐
相关产品推荐

