0

I got an error in ASP.NET MVC, the problem is in action method called Save but I don't know where is it exactly and here is the below error

System.Data.Entity.Validation.DbEntityValidationException: 'Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.'

Customer controller

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);
        }
    }
}

CustomerForm

@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>
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
turki
  • 1
  • 1
  • 1
  • 1
    Does this answer your question? [Getting exact error type in from DbValidationException](https://stackoverflow.com/questions/5345890/getting-exact-error-type-in-from-dbvalidationexception) – Crowcoder Feb 23 '21 at 15:19
  • 1
    Well - did you **look** at those additional errors in the `EntityValidationErrors` property?? What are they telling you? – marc_s Feb 23 '21 at 15:48
  • ErrorMessage "The Name field is required." string PropertyName "Name" string but what i will do now i do not want to remove required on property Name – turki Feb 23 '21 at 16:23
  • @turki, can you provide the related code about CustomerFormViewModel? – Jack J Jun Feb 24 '21 at 06:23
  • aren't you using clientside validation with dataannotations? – Laxmikant Feb 24 '21 at 13:50

4 Answers4

1

It is mainly because some of the required field is null use following method to find exactly what you are missing

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");
} 

And put the debug point at if condition and run the program in debugging mode when the pointer comes to if condition mouse over if if it shows fail then clic over it to see what you are missing

firoz khan
  • 27
  • 7
0

Check your Table if you have Not Null columns, you must add values to those columns in your customers entity before saveChanges()

SHADOW.NET
  • 555
  • 1
  • 5
  • 20
0

I had the same problem and it was that I was not validating in the model the number of characters allowed in a property with respect to the design of the database

Naakmsc
  • 11
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 06 '23 at 13:16
0

Depending on how many fields are in the database table you're trying to save to, it may be easier and quicker to just check to make sure the object you're trying to save to the database has the correct data types and also you are supplying a value for any fields marked "not null". I looked up a fancy "catch" statement and added it, which told me what was wrong from here:

https://www.codeproject.com/Questions/1012001/VALIDATION-FAILED-FOR-ONE-OR-MORE-ENTITIES-SEE-ENT

But aftwerwards I was mad I just didn't check the database model first. It was such a simple problem and easy to fix.

Tom Trost
  • 9
  • 3