20

My app gets the following error:

An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

I get this error when trying to register a new user. Error happens on 'db.SaveChanges()'

Here is the code:

public ActionResult Registration(x.Models.User user)
{
    if(ModelState.IsValid)
    {
        using(var db = new xDBEntities1())
        {
            var crypto = new SimpleCrypto.PBKDF2();
            var encrpPass = crypto.Compute(user.password);
            var sysUser = db.users.Create();
                    
            sysUser.email = user.email;
            sysUser.username = user.username;
            sysUser.password = encrpPass;
            sysUser.premium_credits = 0;
            sysUser.login_times = 0;
            sysUser.last_ip = Request.ServerVariables["REMOTE_ADDR"];
            sysUser.creation_ip = Request.ServerVariables["REMOTE_ADDR"];
            sysUser.banned = 0;
            sysUser.creation_date = DateTime.Now;
            sysUser.creation_time = DateTime.Now.TimeOfDay;

            db.users.Add(sysUser);
            db.SaveChanges();
        }
    }
    return RedirectToAction("Index", "Home");
}

edit: User model class

public class User
{
    [Required]
    [StringLength(50)]
    [Display(Name="Username: ")]
    public String username { get; set; }
    [Required]
    [DataType(DataType.Password)]
    [StringLength(50,MinimumLength=6)]
    [Display(Name="Password: ")]
    public string password { get; set; }
    [Required]
    [EmailAddress]
    [StringLength(50)]
    public string email { get; set; }
    public int phonenumber { get; set; }
    public int mobilephonenumber { get; set; }

    }
}

How can I handle it ?

user2545576
  • 333
  • 1
  • 2
  • 9

7 Answers7

42

To solve this error, we can wrap the SaveChanges() method of DatabaseContext object in try block and in the Catch loop through each errors to find out where the error is. The code goes below.

try
{
    db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
    foreach (var entityValidationErrors in ex.EntityValidationErrors)
    {
        foreach (var validationError in entityValidationErrors.ValidationErrors)
        {
            Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
        }
    }
}

Once the error is found, you can work on that to fix it. Hope this helps.

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
RAVI VAGHELA
  • 877
  • 1
  • 10
  • 12
15

There is some sort of database validation happening preventing you from writing the data into it.

The solution is already stated on this page:

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

As an extra note to this as you are using .net mvc you should use System.Diagnostics.Debug.WriteLine() instead of Console.Writeline() and this will write to the debug output window when you are debugging. As you cannot write to the console when running a mvc project.

Community
  • 1
  • 1
Sebastian
  • 238
  • 2
  • 8
8

You can override the SaveChanges, to handle this exception and provide better exception details.

You can create a class "next" to your context class... the full code for that class is as follow:

using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;

namespace MyNamespace
    {
        public partial class MyContext : DbContext
        {
            // Override base SaveChanges to expand out validation errors so client gets an actually helpful message
            public override int SaveChanges()
            {
                try
                {
                    return base.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    // Retrieve the error messages as a list of strings.
                    var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);

                    // Join the list to a single string.
                    var fullErrorMessage = string.Join("; ", errorMessages);

                    // Combine the original exception message with the new one.
                    var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                    // Throw a new DbEntityValidationException with the improved exception message.
                    throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
                }
            }
        }
    }

Check this for more information: http://devillers.nl/blog/improving-dbentityvalidationexception/

Oggy
  • 1,516
  • 1
  • 16
  • 22
Romias
  • 13,783
  • 7
  • 56
  • 85
3

Even though there is an accepted answer already, my experience could probably help someone in the future. For a quick test you can check the data which you are inputting to the database in Configuration.cs file and then in Model you can check the validation conditions. For example, in my case I would put following validation condition in a model:

[Range(1, 100),DataType(DataType.Currency)]
public decimal Price { get; set; }

And then, inside the Configuration.cs assigning the price to be:

new Photo{
    Title = "Photo 2",
    DateTaken = DateTime.Parse("2013-6-15"),
    Genre = "Nature",
    CameraModel = "Canon",
    Price = 200
}

This, created EntityFrameworkExceptions and prevented database from seeding.

Mukesh Ram
  • 6,248
  • 4
  • 19
  • 37
1

The password Length in the DB and the Model must be >= that the length of encrpPass.

Source007
  • 11
  • 2
1

Check the size of the database fields that you are trying to save data to. Changing a field from varchar(50) to varchar(max) did the trick for me.

If you are using Entity Framework you might have to delete and add the table that you made changes to.

stink
  • 865
  • 8
  • 19
0

Maybe this is helpful for someone : This error occurred because I changed the field properties in EF SQL Server DB from var(100) to var(200). I updated properly in the DB, but forgot to update the ADO properties. In the .edmx file you can click on the columnname and change the properties, after that it worked for me.

c_ph_r
  • 207
  • 3
  • 13