Search code examples
c#asp.net-mvcvalidationef-code-firstregistration

Validation failed for one or more entities. Validations added in Model


This validation exception comes when I press the Register button in the form in Register.cshtml view page.

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

@*Registration form*@
     <section class="registersection">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <form action="~/Users/SaveRegister" method="post">
                            @using (Html.BeginForm())
                            {
                                @Html.ValidationSummary(true)

                                @Html.AntiForgeryToken()
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.user_name)
                                </div>
                                <div class="editor-field">
                                    @Html.EditorFor(model => model.user_name)
                                    @Html.ValidationMessageFor(model => model.user_name)
                                </div>

                                <div class="editor-label">
                                    @Html.LabelFor(model => model.user_passport)
                                </div>
                                <div class="editor-field">
                                    @Html.EditorFor(model => model.user_passport)
                                    @Html.ValidationMessageFor(model => model.user_passport)
                                </div>
                                <p>
                                    <input type="submit" value="Register" />
                                </p>
                            }
                        </form>

                    </div>
                </div>
            </div>
      </section>

My User Model

@*Program.cs@* Model

public class User
        {   
            public int userid { get; set; }

            [Display(Name ="Passenger Name")]
            [Required(ErrorMessage ="Your name is required")]
            public string user_name { get; set; }

            [Display(Name = "Passenger Father Name")]
            [Required(ErrorMessage = "Your Father name is required")]
            public string user_fname { get; set; }

            [Required]
            [Display(Name = "CNIC")]
            [RegularExpression(@"^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$", ErrorMessage = "Entered CNIC format is not valid.")]
           public string usercnic { get; set; }

            [StringLength(8, MinimumLength = 7)]
            public string user_passport { get; set; }
            [StringLength(15, MinimumLength = 10)]
            public string user_bloodGp { get; set; }
            [StringLength(35, MinimumLength = 30)]
            public string user_nationality { get; set; }
            public string usertype { get; set; }
            public string status { get; set; }
            [Required]
            [Range(0,8)]
            public int mobilenumber { get; set; }
            public string gender { get; set; }

        }

    public class BloggingContext : DbContext
    {
        public DbSet<Plane> Planes { get; set; }
        public DbSet<User>  Users { get; set; }
    }

I have added this in global.asax Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
          Database.SetInitializer<AirlineappContext>(new DropCreateDatabaseIfModelChanges<AirlineappContext>());

        }

Solution

  • Surround your code with a try catch block to catch and log the DbEntityValidationException so you get more information about the error.

    public void AppendValidationErrors(Exception e)
    {
        DbEntityValidationException ex = e is DbEntityValidationException ?
            e as DbEntityValidationException : null ;
    
        if (ex == null) { log.Info(e); return; }
    
        foreach (var eve in ex.EntityValidationErrors)
        {
            log.Info(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)
            {
                log.Info(string.Format("- Property: \"{0}\", Error: \"{1}\"",
                    ve.PropertyName, ve.ErrorMessage));
            }
        }
    }