Skip to content
Fix Code Error

Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details

March 13, 2021 by Code Error
Posted By: Anonymous

I am having this error when seeding my database with code first approach.

Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.

To be honest I don’t know how to check the content of the validation errors. Visual Studio shows me that it’s an array with 8 objects, so 8 validation errors.

This was working with my previous model, but I made a few changes that I explain below:

  • I had an enum called Status, I changed it to a class called Status
  • I changed the class ApplicantsPositionHistory to have 2 foreign key to the same table

Excuse me for the long code, but I have to paste it all. The exception is thrown in the last line of the following code.

namespace Data.Model
{  
    public class Position
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]   
        public int PositionID { get; set; }

        [Required(ErrorMessage = "Position name is required.")]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Name should not be longer than 20 characters.")]
        [Display(Name = "Position name")]              
        public string name { get; set; }

        [Required(ErrorMessage = "Number of years is required")] 
        [Display(Name = "Number of years")]        
        public int yearsExperienceRequired { get; set; }

        public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
    }

    public class Applicant
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]      
        public int ApplicantID { get; set; }

        [Required(ErrorMessage = "Name is required")] 
        [StringLength(20, MinimumLength = 3, ErrorMessage="Name should not be longer than 20 characters.")]
        [Display(Name = "First and LastName")]
        public string name { get; set; }

        [Required(ErrorMessage = "Telephone number is required")] 
        [StringLength(10, MinimumLength = 3, ErrorMessage = "Telephone should not be longer than 20 characters.")]
        [Display(Name = "Telephone Number")]
        public string telephone { get; set; }

        [Required(ErrorMessage = "Skype username is required")] 
        [StringLength(10, MinimumLength = 3, ErrorMessage = "Skype user should not be longer than 20 characters.")]
        [Display(Name = "Skype Username")]
        public string skypeuser { get; set; }

        public byte[] photo { get; set; }

        public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
    }

    public class ApplicantPosition
    {
        [Key]
        [Column("ApplicantID", Order = 0)]
        public int ApplicantID { get; set; }

        [Key]
        [Column("PositionID", Order = 1)]
        public int PositionID { get; set; }

        public virtual Position Position { get; set; }

        public virtual Applicant Applicant { get; set; }

        [Required(ErrorMessage = "Applied date is required")] 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Display(Name = "Date applied")]     
        public DateTime appliedDate { get; set; }

        [Column("StatusID", Order = 0)]
        public int StatusID { get; set; }

        public Status CurrentStatus { get; set; }

        //[NotMapped]
        //public int numberOfApplicantsApplied
        //{
        //    get
        //    {
        //        int query =
        //             (from ap in Position
        //              where ap.Status == (int)Status.Applied
        //              select ap
        //                  ).Count();
        //        return query;
        //    }
        //}
    }

    public class Address
    {
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Country should not be longer than 20 characters.")]
        public string Country { get; set; }

        [StringLength(20, MinimumLength = 3, ErrorMessage = "City  should not be longer than 20 characters.")]
        public string City { get; set; }

        [StringLength(50, MinimumLength = 3, ErrorMessage = "Address  should not be longer than 50 characters.")]
        [Display(Name = "Address Line 1")]     
        public string AddressLine1 { get; set; }

        [Display(Name = "Address Line 2")]
        public string AddressLine2 { get; set; }   
    }

    public class ApplicationPositionHistory
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
        public int ApplicationPositionHistoryID { get; set; }

        public ApplicantPosition applicantPosition { get; set; }

        [Column("oldStatusID")]
        public int oldStatusID { get; set; }

        [Column("newStatusID")]
        public int newStatusID { get; set; }

        public Status oldStatus { get; set; }

        public Status newStatus { get; set; }

        [StringLength(500, MinimumLength = 3, ErrorMessage = "Comments  should not be longer than 500 characters.")]
        [Display(Name = "Comments")]
        public string comments { get; set; }

        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Display(Name = "Date")]     
        public DateTime dateModified { get; set; }
    }

    public class Status
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
        public int StatusID { get; set; }

        [StringLength(20, MinimumLength = 3, ErrorMessage = "Status  should not be longer than 20 characters.")]
        [Display(Name = "Status")]
        public string status { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.IO;

namespace Data.Model
{
    public class HRContextInitializer : DropCreateDatabaseAlways<HRContext>
    {
        protected override void Seed(HRContext context)
        {
            #region Status
            Status applied = new Status() { status = "Applied" };
            Status reviewedByHR = new Status() { status = "Reviewed By HR" };
            Status approvedByHR = new Status() { status = "Approved by HR" };
            Status rejectedByHR = new Status() { status = "Rejected by HR" };
            Status assignedToTechnicalDepartment = new Status() { status = "Assigned to Technical Department" };
            Status approvedByTechnicalDepartment = new Status() { status = "Approved by Technical Department" };
            Status rejectedByTechnicalDepartment = new Status() { status = "Rejected by Technical Department" };

            Status assignedToGeneralManager = new Status() { status = "Assigned to General Manager" };
            Status approvedByGeneralManager = new Status() { status = "Approved by General Manager" };
            Status rejectedByGeneralManager = new Status() { status = "Rejected by General Manager" };

            context.Status.Add(applied);
            context.Status.Add(reviewedByHR);
            context.Status.Add(approvedByHR);
            context.Status.Add(rejectedByHR);
            context.Status.Add(assignedToTechnicalDepartment);
            context.Status.Add(approvedByTechnicalDepartment);
            context.Status.Add(rejectedByTechnicalDepartment);
            context.Status.Add(assignedToGeneralManager);
            context.Status.Add(approvedByGeneralManager);
            context.Status.Add(rejectedByGeneralManager); 
            #endregion    

            #region Position
            Position netdeveloper = new Position() { name = ".net developer", yearsExperienceRequired = 5 };
            Position javadeveloper = new Position() { name = "java developer", yearsExperienceRequired = 5 };
            context.Positions.Add(netdeveloper);
            context.Positions.Add(javadeveloper); 
            #endregion

            #region Applicants
            Applicant luis = new Applicant()
            {
                name = "Luis",
                skypeuser = "le.valencia",
                telephone = "0491732825",
                photo = File.ReadAllBytes(@"C:UsersLUIS.SIMBIOSDocumentsVisual Studio 2010ProjectsSlnHRHRRazorFormsContentpictures1.jpg")
            };

            Applicant john = new Applicant()
            {
                name = "John",
                skypeuser = "jo.valencia",
                telephone = "3435343543",
                photo = File.ReadAllBytes(@"C:UsersLUIS.SIMBIOSDocumentsVisual Studio 2010ProjectsSlnHRHRRazorFormsContentpictures2.jpg")
            };

            context.Applicants.Add(luis);
            context.Applicants.Add(john); 
            #endregion

            #region ApplicantsPositions
            ApplicantPosition appicantposition = new ApplicantPosition()
            {
                Applicant = luis,
                Position = netdeveloper,
                appliedDate = DateTime.Today,
                StatusID = 1
            };

            ApplicantPosition appicantposition2 = new ApplicantPosition()
            {
                Applicant = john,
                Position = javadeveloper,
                appliedDate = DateTime.Today,
                StatusID = 1
            };        

            context.ApplicantsPositions.Add(appicantposition);            
            context.ApplicantsPositions.Add(appicantposition2); 
            #endregion

            context.SaveChanges(); --->> Error here
        }
    }
}

Solution

To be honest I don’t know how to check the content of the validation errors. Visual Studio shows me that it’s an array with 8 objects, so 8 validation errors.

Actually you should see the errors if you drill into that array in Visual studio during debug. But you can also catch the exception and then write out the errors to some logging store or the console:

try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges

context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type "{0}"" in state ""{1}"" has the following validation errors:""

Answered By: Anonymous

Related Articles

  • TypeScript metadata reflection references other…
  • Compiler error: "class, interface, or enum expected"
  • How to add "on delete cascade" constraints?
  • MySQL user DB does not have password columns -…
  • How does PHP 'foreach' actually work?
  • How to Detect if I'm Compiling Code with a…
  • GLYPHICONS - bootstrap icon font hex value
  • Database development mistakes made by application developers
  • For-each over an array in JavaScript
  • Unity Scripts edited in Visual studio don't provide…
  • Why is enum class preferred over plain enum?
  • Detect if Visual C++ Redistributable for Visual…
  • enum to string in modern C++11 / C++14 / C++17 and…
  • DbEntityValidationException - How can I easily tell…
  • MySQL : ERROR 1215 (HY000): Cannot add foreign key…
  • vue v-for of typescript enum
  • Adding a guideline to the editor in Visual Studio
  • error LNK2005: ✘✘✘ already defined in…
  • How to Update Database from Assets Folder in App
  • How can I represent an 'Enum' in Python?
  • SQL query return data from multiple tables
  • What is a typedef enum in Objective-C?
  • EntityMetadataNotFound: No metadata for…
  • MySQL Data Source not appearing in Visual Studio
  • MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'
  • What's the best way to get the last element of an…
  • How to completely uninstall Visual Studio 2010?
  • Integrating JSON feed with Backbone JS
  • How Should I Declare Foreign Key Relationships Using…
  • Cannot change column used in a foreign key constraint
  • Load array of Enum values from Json file
  • Could not load file or assembly…
  • CMake error at CMakeLists.txt:30 (project): No…
  • Conveniently map between enum and int / String
  • What is the difference between Visual Studio Express…
  • laravel vuejs/axios put request Formdata is empty
  • Can't add C# class in visual studio 2019 anymore -…
  • Foreign key constraints: When to use ON UPDATE and ON DELETE
  • How to filter a RecyclerView with a SearchView
  • The 'compilation' argument must be an instance of…
  • Visual Studio 2013 License Product Key
  • sql query to find priority jobs
  • Backbone.js Backbone.wrapError function
  • Enum "Inheritance"
  • Why cat does not work with parameter -0 in xargs?
  • Java using enum with switch statement
  • MySQL Cannot Add Foreign Key Constraint
  • Where is the documentation for the values() method of Enum?
  • Using SSIS BIDS with Visual Studio 2012 / 2013
  • Visual Studio debugging/loading very slow
  • How can I iterate over an enum?
  • enum - getting value of enum on string conversion
  • How do I include certain conditions in SQL Count
  • How to get names of enum entries?
  • Error Code: 1005. Can't create table '...' (errno: 150)
  • Seed data with relations to an object with unknown ID
  • Code-first vs Model/Database-first
  • Add a reference column migration in Rails 4
  • How should a model be structured in MVC?
  • Handling errors with the (now default) Ember Data…
  • How can I find the product GUID of an installed MSI setup?
  • Visual Studio 2015 or 2017 does not discover unit tests
  • Enum Naming Convention - Plural
  • Smart way to truncate long strings
  • Change underlying enum value in Postgres
  • The relationship could not be changed because one or…
  • How to dynamically add and remove views with Ember.js
  • How to convert networkx node positions to…
  • Oracle (ORA-02270) : no matching unique or primary…
  • MySQL Cannot drop index needed in a foreign key constraint
  • Get operating system info
  • Layout doesn't expand more than initial size it was…
  • The definitive guide to form-based website authentication
  • How to get the Display Name Attribute of an Enum…
  • Visual Studio 2010 always thinks project is out of…
  • What's the advantage of a Java enum versus a class…
  • Using Java with Microsoft Visual Studio 2012
  • C++ OpenGL stb_image.h errors
  • Force uninstall of Visual Studio
  • JavaScript hashmap equivalent
  • Using Aurelia validation in model
  • Java SSLHandshakeException "no cipher suites in common"
  • Next.js - Warning: Prop `dangerouslySetInnerHTML`…
  • Is it possible to apply CSS to half of a character?
  • Forward declaring an enum in C++
  • How to run enum functions with conditions of another…
  • Map enum in JPA with fixed values?
  • Save child objects automatically using JPA Hibernate
  • MySQL - Cannot add or update a child row: a foreign…
  • What is an IndexOutOfRangeException /…
  • Create MSI or setup project with Visual Studio 2012
  • Error message "No exports were found that match the…
  • Cannot open include file: 'stdio.h' - Visual Studio…
  • Group array of objects by multiple keys using d3.groups
  • How to change the foreign key referential action? (behavior)
  • A default parent router with child routers
  • Enum - type of a specific interface without implementing it
  • Improve INSERT-per-second performance of SQLite
  • What are the differences between Visual Studio Code…
  • Ways to save Backbone.js model data?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to add a list item to an existing unordered list?

Next Post:

Call a REST API in PHP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error