[c#] Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

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:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\1.jpg")
            };

            Applicant john = new Applicant()
            {
                name = "John",
                skypeuser = "jo.valencia",
                telephone = "3435343543",
                photo = File.ReadAllBytes(@"C:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\2.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
        }
    }
}

The answer is


While you are in debug mode within the catch {...} block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:

((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors

or:

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

If you are not in a try/catch or don't have access to the exception object.

This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.


Was also struggling with this error and based on the topic here and this answer was able to figure out snippet to copy/paste without the need to figure out what has to be imported (excellent for C# beginners), code below:

try
{
  context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
  foreach (var entityValidationErrors in ex.EntityValidationErrors)
  {
    foreach (var validationError in entityValidationErrors.ValidationErrors)
    {
      System.Diagnostics.Debug.WriteLine("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
    }
  }
}

In my case it was because of the length of the database field is less than the length of the input field.

database table

create table user(
  Username nvarchar(5) not  null
);

My input

User newUser = new User()
{
   Username = "123456"
};

the value for Username length is 5 which is lessthan 6

...this may help someone


Note that Entity.GetType().BaseType.Name gives the type name you specified, not the one with all the hex digits in its name.


In debug, you can enter this in your QuickWatch expression evaluator entry field:

context.GetValidationErrors()

If you are simply catching a generic exception, it may benefit you to cast this as a DbEntityValidationException. This type of an exception has a Validation Errors property, and continuing to expand your way into them, you will find all the problems.

For example, if you put a break point in the catch, you can throw the following into a watch:

((System.Data.Entity.Validation.DbEntityValidationException ) ex)

An example of an error is if a field does not allow nulls, and you have a null string, you'll see it say that the field is required.


For anyone who works in VB.NET

Try
Catch ex As DbEntityValidationException
    For Each a In ex.EntityValidationErrors
        For Each b In a.ValidationErrors
            Dim st1 As String = b.PropertyName
            Dim st2 As String = b.ErrorMessage
        Next
    Next
End Try

This could actually do it without having to write code:

In your catch block, add a break point at the following line of code:

catch (Exception exception)
{

}

Now if you hover on exception or add it to the Watch and then navigate into the exception details as shown below; you will see which particular column(s) is/ are causing the problem as this error usually occurs when a table-constraint is violated..

enter image description here

Large image


Check whether you have Not Null constraint in your table columns and you are not passes the value for that column while insert/Update operations. That Causes this exception in entity framework.


The answer from @Slauma is really great but I found that it didnt't work when a ComplexType property was invalid.

For example, say you have a property Phone of the complex type PhoneNumber. If the AreaCode property is invalid, the property name in ve.PropertyNames is "Phone.AreaCode". This causes the call to eve.Entry.CurrentValues<object>(ve.PropertyName) to fail.

To fix this, you can split the property name at each ., then recurse through the resulting array of property names. Finally, when you arrive at the bottom of the chain, you can simply return the value of the property.

Below is @Slauma's FormattedDbEntityValidationException class with support for ComplexTypes.

Enjoy!

[Serializable]
public class FormattedDbEntityValidationException : Exception
{
    public FormattedDbEntityValidationException(DbEntityValidationException innerException) :
        base(null, innerException)
    {
    }

    public override string Message
    {
        get
        {
            var innerException = InnerException as DbEntityValidationException;
            if (innerException == null) return base.Message;

            var sb = new StringBuilder();

            sb.AppendLine();
            sb.AppendLine();
            foreach (var eve in innerException.EntityValidationErrors)
            {
                sb.AppendLine(string.Format("- Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().FullName, eve.Entry.State));
                foreach (var ve in eve.ValidationErrors)
                {
                    object value;
                    if (ve.PropertyName.Contains("."))
                    {
                        var propertyChain = ve.PropertyName.Split('.');
                        var complexProperty = eve.Entry.CurrentValues.GetValue<DbPropertyValues>(propertyChain.First());
                        value = GetComplexPropertyValue(complexProperty, propertyChain.Skip(1).ToArray());
                    }
                    else
                    {
                        value = eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName);
                    }
                    sb.AppendLine(string.Format("-- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
                        ve.PropertyName,
                        value,
                        ve.ErrorMessage));
                }
            }
            sb.AppendLine();

            return sb.ToString();
        }
    }

    private static object GetComplexPropertyValue(DbPropertyValues propertyValues, string[] propertyChain)
    {
        var propertyName = propertyChain.First();
        return propertyChain.Count() == 1 
            ? propertyValues[propertyName] 
            : GetComplexPropertyValue((DbPropertyValues)propertyValues[propertyName], propertyChain.Skip(1).ToArray());
    }
}

What i found...when i got 'EntityValidationErrors' error is that....i have a field in my database 'db1' in table 'tbladdress' as 'address1' which has size of 100 (i.e address varchar(100) null) and i was passing value more than 100 characters..and this leading to error while saving data to database....

So you must Check the data you are passing to the field.


Here's another way to do it instead of using foreach loops for looking inside EntityValidationErrors. Of course you can format the message to your own liking :

try {
        // your code goes here...
    } 
catch (DbEntityValidationException ex) 
    {
        Console.Write($"Validation errors: {string.Join(Environment.NewLine, ex.EntityValidationErrors.SelectMany(vr => vr.ValidationErrors.Select(err => $"{err.PropertyName} - {err.ErrorMessage}")))}", ex);
        throw;
    }

Just throwing my two cents in...

Within my dbConfiguration.cs, I like to wrap my context.SaveChanges() method into a try/catch and produce an output text file that allows me to read the Error(s) clearly, and this code also timestamps them - handy if you run into more than one error at different times!

        try
        {
            context.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            //Create empty list to capture Validation error(s)
            var outputLines = new List<string>();

            foreach (var eve in e.EntityValidationErrors)
            {
                outputLines.Add(
                    $"{DateTime.Now}: Entity of type \"{eve.Entry.Entity.GetType().Name}\" in state \"{eve.Entry.State}\" has the following validation errors:");
                outputLines.AddRange(eve.ValidationErrors.Select(ve =>
                    $"- Property: \"{ve.PropertyName}\", Error: \"{ve.ErrorMessage}\""));
            }
            //Write to external file
            File.AppendAllLines(@"c:\temp\dbErrors.txt", outputLines);
            throw;
        }

I had to write this in the Immediate window :3

(((exception as System.Data.Entity.Validation.DbEntityValidationException).EntityValidationErrors as System.Collections.Generic.List<System.Data.Entity.Validation.DbEntityValidationResult>)[0].ValidationErrors as System.Collections.Generic.List<System.Data.Entity.Validation.DbValidationError>)[0]

in order to get deep into the exact error !


Catch the exception in a try catch and then quick watch or ctrl+d & ctrl+q and you can drill down to the EntityValidationErrors.


This works for me.

var modelState = ModelState.Values;
if (!ModelState.IsValid)
{
    return RedirectToAction("Index", "Home", model);
}

Put a breakpoint on if statement. Then you can check modelState in debug windows. On every value you can see if there is an error and even the error message. That's it. When you don't need it anymore, just delete or comment the line.

I hope this will help.

If asked, I can provide detailed screenshot in the debug window.


This error occurs mostly because of field size. CHECK all the field sizes in a database table.


You can do it from Visual Studio during debugging without writing any code, not even a catch block.

Just add a watch with the name:

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

The watch expression $exception displays any exception thrown in the current context, even if it has not been caught and assigned to a variable.

Based on http://mattrandle.me/viewing-entityvalidationerrors-in-visual-studio/


I also faced the same problem. I updated my .edmx from the database after that the exception has vanished.


If you're using IIS with Windows Authentification and Entity Framework, be careful to use authorize.

I tried to POST without authorize and it didn't work, and get this error on db.SaveChangesAsync();, while all other verbs GET and DELETE were working.

But when I added AuthorizeAttribute as annotation, it worked.

[Authorize]
public async Task<IHttpActionResult> Post(...){
....
}

I faced this error before

when I tried to update specific field in my model in entity framwork

Letter letter = new Letter {ID = letterId, ExportNumber = letterExportNumber,EntityState = EntityState.Modified};
LetterService.ChangeExportNumberfor(letter);
//----------


public int ChangeExportNumber(Letter letter)
    {
        int result = 0;
        using (var db = ((LettersGeneratorEntities) GetContext()))
        {
            db.Letters.Attach(letter);
            db.Entry(letter).Property(x => x.ExportNumber).IsModified = true;
            result += db.SaveChanges();
        }
        return result;
    }

and according the above answers

I found the Validation message The SignerName field is required.

which pointing to field in my model

and when I checked my database schema I found

enter image description here

so off coure ValidationException has its right to raise

and according to this field I want it to be nullable, (I dont know how I messed it)

so I changed that field to allow Null, and by this my code will not give me this error again

so This error maybe will happened if you invalidate Your Data integrity of your database


Please check the fields value you are passing, are valid and according to database fields. For example number of characters passed in a particular field are less than the characters defined in database table field.


Here's how you can check the contents of the EntityValidationErrors in Visual Studio (without writing any extra code) i.e. during Debugging in the IDE.

The Problem?

You are right, the Visual Studio debugger's View Details Popup doesn't show the actual errors inside the EntityValidationErrors collection .

enter image description here

The Solution!

Just add the following expression in a Quick Watch window and click Reevaluate.

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

In my case, see how I am able to expand into the ValidationErrors List inside the EntityValidationErrors collection

enter image description here

References: mattrandle.me blog post, @yoel's answer


For a quick way to see the first error without even adding a watch you can paste this in the Immediate Window:

((System.Data.Entity.Validation.DbEntityValidationException)$exception)
    .EntityValidationErrors.First()
    .ValidationErrors.First()

Per @Slauma's answer and @Milton's suggestion I've extended our base class's custom save method with a try/catch that will handle (and hence log in our error logging!) these sorts of exceptions.

// Where `BaseDB` is your Entities object... (it could be `this` in a different design)
public void Save(bool? validateEntities = null)
{
    try
    {
        //Capture and set the validation state if we decide to
        bool validateOnSaveEnabledStartState = BaseDB.Configuration.ValidateOnSaveEnabled;
        if (validateEntities.HasValue)
            BaseDB.Configuration.ValidateOnSaveEnabled = validateEntities.Value;

        BaseDB.SaveChanges();

        //Revert the validation state when done
        if (validateEntities.HasValue)
            BaseDB.Configuration.ValidateOnSaveEnabled = validateOnSaveEnabledStartState;
    }
    catch (DbEntityValidationException e)
    {
        StringBuilder sb = new StringBuilder();
        foreach (var eve in e.EntityValidationErrors)
        {
            sb.AppendLine(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", 
                                            eve.Entry.Entity.GetType().Name,
                                            eve.Entry.State));
            foreach (var ve in eve.ValidationErrors)
            {
                sb.AppendLine(string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                            ve.PropertyName,
                                            ve.ErrorMessage));
            }
        }
        throw new DbEntityValidationException(sb.ToString(), e);
    }
}

just Check Your Database Table Field Length . Your Input Text Is Greater than the length of column field data type length


Using the answer of @Slauma i have made a code snippet (a surrounds with snippet) for better use.

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
      <Title>ValidationErrorsTryCatch</Title>
      <Author>Phoenix</Author>
      <Description>
      </Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>
      </Shortcut>
    </Header>
    <Snippet>
      <Code Language="csharp"><![CDATA[try
{
    $selected$ $end$
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

As mentioned in other posts, simply catch the exception in DbEntityValidationException class. Which will give you watever you required during error cases.

 try
 {
  ....
 }
 catch(DbEntityValidationException ex)
 {
  ....
 }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to entity-framework-4

Entity Framework Join 3 Tables Entity framework self referencing loop detected The object 'DF__*' is dependent on column '*' - Changing int to double LEFT JOIN in LINQ to entities? Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why? The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties How to include a child object's child object in Entity Framework 5 EF Migrations: Rollback last applied migration? The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Examples related to entity-framework-4.1

Entity Framework Join 3 Tables How to include a child object's child object in Entity Framework 5 Ignoring a class property in Entity Framework 4.1 Code First The type or namespace name 'Entity' does not exist in the namespace 'System.Data' Validation failed for one or more entities. See 'EntityValidationErrors' property for more details StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First Entity framework code-first null foreign key How do I detach objects in Entity Framework Code First? Entity Framework Code First - two Foreign Keys from same table How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?