.NET Core,简单产品和类别模型上的AllowNull 导航属性的模型状态无效

问题描述 投票:0回答:1

类别和产品之间存在一对多的关系。 我正在尝试使用实体框架(脚手架)提供的默认控制器和视图创建新类别或编辑类别。

每当我尝试创建/编辑类别时,模型状态就会变得无效。 ProductContoller 也发生这种情况。

欢迎任何建议或线索!!!

感谢您的宝贵时间...

我的模特:

public class Product
{
    [Key]
    public int ProductId { get; set; }

    // Foreign Key
    [ForeignKey("CategoryId")]
    public int CategoryID { get; set; }

    public Categories Category { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }
    public string url { get; set; }
    public decimal Price { get; set; }
}

public class Categories
{
    [Key]
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string url { get; set; }

    // Navigation Property for Products (optional but recommended)
    [AllowNull]
    public ICollection<Product> Products { get; set; }
}
// In your Models folder (or create a ViewModels folder)
public class ProductsCategoriesViewModel
{
    public List<Categories> Categories { get; set; }
    public List<Product> Products { get; set; }
}

默认CreateController(使用脚手架):

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("CategoryID,CategoryName,url")] Categories categories)
        {
            if (ModelState.IsValid)
            {
                _context.Add(categories);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(categories);
        }

创建.cshtml:

@model MyKartV2.Models.Categories

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Categories</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="CategoryName" class="control-label"></label>
                <input asp-for="CategoryName" class="form-control" />
                <span asp-validation-for="CategoryName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="url" class="control-label"></label>
                <input asp-for="url" class="form-control" />
                <span asp-validation-for="url" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

编辑: 尽管我的表单仅提交 2 个字段,即 CategoryName 和 url,但为什么 ModelState 还要检查 Products 导航属性。

modelState 变得无效,因为它正在 ModelState 中添加导航属性(产品)的条目。 我得到的错误是

 "The Products field is required."

ModeState Entries

c# .net asp.net-core model-view-controller modelstate
1个回答
0
投票

从当前的模型定义来看,.NET 不知道哪些属性是导航属性。而且根据您使用的 .NET 版本,可能会强制执行可空性。因此,您需要指定某些属性可以为空。

通常在定义导航属性时使用 virtual 关键字来完成。至于可空性,您需要添加一个 ?在对象定义之后指定创建该类的实例时导航属性可以为 null。

您的模型定义应如下所示:

public class Product
{
    [Key]
    public int ProductId { get; set; }

    // Foreign Key
    [ForeignKey("CategoryId")]
    public int CategoryID { get; set; }

    public virtual Categories? Category { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }
    public string url { get; set; }
    public decimal Price { get; set; }
}

public class Categories
{
    [Key]
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string url { get; set; }

    // Navigation Property for Products (optional but recommended)
    public virtual ICollection<Product>? Products { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.