Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle System.Data.Entity.Validation.DbEntityValidationException? [duplicate]

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 ?

like image 743
user2545576 Avatar asked Feb 06 '14 15:02

user2545576


People also ask

How do you fix validation failed for one or more entities see EntityValidationErrors property for more details?

Error: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. solution: correct your Data Model according to your database SET fieldNames or length.

What is DbEntityValidationException?

DbEntityValidationException is the exception thrown by Entity Framework when entity validation fails. While this exception is extremely valuable, the exception message omits the most important bit of information: The actual validation errors.


2 Answers

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.

like image 195
RAVI VAGHELA Avatar answered Sep 20 '22 18:09

RAVI VAGHELA


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.

like image 40
Sebastian Avatar answered Sep 18 '22 18:09

Sebastian