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

Entity Framework Core 1:n关系模型创建记录遇验证错误求助

问题解决:表单提交时Items字段必填验证错误

问题背景

提交创建ItemCategory的表单时,出现验证错误:

The Items field is required.

但表单并未包含Items字段,且仅需创建ItemCategory对象,不想使用DTO手动映射。

解决方案(无需DTO)

方法1:添加[BindNever]特性忽略模型绑定

修改ItemCategory模型中的Items属性,添加[BindNever]特性,告知模型绑定器跳过该属性:

using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace NVFlexo.Models;

[Index(nameof(CategoryName), IsUnique = true)]
public class ItemCategory
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string CategoryName { get; set; }
    
    [BindNever]
    public List<Item> Items { get; }
}

方法2:在控制器中移除Items的验证错误

在控制器的Create方法中,判断ModelState.IsValid之前,手动移除Items字段的验证错误:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(ItemCategory obj)
{
    ModelState.Remove(nameof(ItemCategory.Items));
    
    if (ModelState.IsValid)
    {
        _db.ItemCategories.Add(obj);
        _db.SaveChanges();
        TempData["success"] = "Item Category Created Successfully";
        return RedirectToAction("Index");
    }
    return View(obj);
}

注:原代码中TempData["success"]的位置错误,应放在SaveChanges()成功后,否则验证失败时也会显示成功提示,建议调整。

方法3:初始化Items集合

将Items属性初始化为空集合,模型绑定器会识别到它已存在,不会触发必填验证:

public class ItemCategory
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string CategoryName { get; set; }
    
    public List<Item> Items { get; } = new List<Item>();
}

原因说明

Items属性只有getter没有setter,ASP.NET Core模型绑定器无法为其赋值,因此默认将其标记为必填项,触发验证错误。上述三种方法都能绕过这个问题,无需使用DTO。

内容的提问来源于stack exchange,提问作者Ela Buwa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:57:30