【问题标题】:i got Validation failed for one or more entities. See 'EntityValidationErrors' property for more details我得到一个或多个实体的验证失败。有关更多详细信息,请参阅“EntityValidationErrors”属性
【发布时间】:2021-05-25 21:03:20
【问题描述】:

我在 ASP.NET MVC 中遇到错误,问题出在名为 Save 的操作方法中,但我不知道它到底在哪里,这是下面的错误

System.Data.Entity.Validation.DbEntityValidationException: '一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。'

客户控制

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Vidly.Context;
using Vidly.Models;
using Vidly.VewModels;

namespace Vidly.Controllers
{
    public class CustomersController : Controller
    {
        private  MyDbContext _contex;
        
        public CustomersController()
        {
            _contex = new MyDbContext();
        }

        protected override void Dispose(bool disposing)
        {
            _contex.Dispose();
        }

        public IActionResult New()
        {
            var membershipTypes = _contex.MembershipTypes.ToList();
            var ViewModel = new CustomerFormViewModel
            {
                MembershipTypes = membershipTypes
            };
            return View("CustomerForm",ViewModel);
        }

        [HttpPost]
        public IActionResult Save(Customer customer)
        {
            if (customer.Id == 0)
                _contex.Customers.Add(customer);
            else
            {
                var customerInDb = _contex.Customers.Single(c => c.Id == customer.Id);

                customerInDb.Name = customer.Name;
                customerInDb.BirthDate = customer.BirthDate;
                customerInDb.MembershipTypeId = customer.MembershipTypeId;
                customerInDb.IsSubscribedToNewsLetter = customer.IsSubscribedToNewsLetter;
           }

           // doing here my logic
           _contex.SaveChanges();
            
            return RedirectToAction("Index","customers");
        }

        public IActionResult Edit(int id)
        {
            var customer = _contex.Customers.SingleOrDefault(c => c.Id == id);

            if (customer == null)
                 return Content("not found");

            var ViewModel = new CustomerFormViewModel
            {
                customers = customer,
                MembershipTypes = _contex.MembershipTypes.ToList()
            };

            return View("customerForm",ViewModel); 
        }

        public IActionResult Index()
        {
            var customers = _contex.Customers.Include(c => c.MembershipType).ToList();
            return View(customers);
        }

        public IActionResult Details(int id)
        {
            var customers = _contex.Customers.Include(c => c.MembershipType).SingleOrDefault(c => c.Id == id);

            return View(customers);
        }
    }
}

客户表格

@model Vidly.VewModels.CustomerFormViewModel
@{
    ViewData["Title"] = "New";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>New</h1>

@using (Html.BeginForm("Save", "customers"))
{
    <div class="form-group">
        @Html.LabelFor(m => m.customers.Name)
        @Html.TextBoxFor(m => m.customers.Name, new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.customers.BirthDate)
        @Html.TextBoxFor(m => m.customers.BirthDate, "{0:d MMM yyyy}", new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.customers.MembershipTypeId)
        @Html.DropDownListFor(m => m.customers.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "Name"), "Select Membership Type", new { @class = "form-control" })
    </div>
    <div class="checkbox">
        @*<input class="form-check-input" type="checkbox" value="" id="flexCheckChecked" checked>*@
        <label>
            @Html.CheckBoxFor(m => m.customers.IsSubscribedToNewsLetter) Subscribed To NewsLetter?
        </label>
    </div>
    @Html.HiddenFor(m => m.customers.Id)
    <button type="submit" class="btn btn-primary">Save</button>
}

【问题讨论】:

  • 嗯 - 您是否查看 EntityValidationErrors 属性中的其他错误?他们在告诉你什么?
  • 错误消息“名称字段是必需的。” string PropertyName "Name" string 但我现在要做什么我不想删除属性名称上的必需项
  • @turki,能否提供CustomerFormViewModel的相关代码?
  • 你不是在使用带有数据注释的客户端验证吗?

标签: c# asp.net visual-studio model-view-controller


【解决方案1】:

这主要是因为某些必填字段为空,请使用以下方法准确查找您缺少的内容

if (ModelState.IsValid)
{
   //Your code come here
   if (customer.Id == 0)
            _contex.Customers.Add(customer);
        else
        {
            var customerInDb = _contex.Customers.Single(c => c.Id == customer.Id);

            customerInDb.Name = customer.Name;
            customerInDb.BirthDate = customer.BirthDate;
            customerInDb.MembershipTypeId = customer.MembershipTypeId;
            customerInDb.IsSubscribedToNewsLetter = customer.IsSubscribedToNewsLetter;
       }

       // doing here my logic
       _contex.SaveChanges();
        
        return RedirectToAction("Index","customers");
} 

并将调试点置于 if 条件并以调试模式运行程序 当指针到达 if 条件时,如果它显示失败,则鼠标悬停,然后单击它以查看您缺少的内容

【讨论】:

    【解决方案2】:

    如果您有Not Null 列,请检查您的表格,您必须在customers entity 中的saveChanges() 之前向这些列添加值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 2011-12-09
      • 1970-01-01
      • 2018-01-10
      • 2013-05-13
      • 2014-02-24
      • 1970-01-01
      相关资源
      最近更新 更多