Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I got this 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.

===========================================
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;

namespace ParkingMvcApp.Models
{
    [MetadataType(typeof(ClientMetaData))]

    public partial class Client
    {
        [DataType("Password")]
        [System.Web.Mvc.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

    public class ClientMetaData
    {
        [StringLength(10, MinimumLength = 10, ErrorMessage = "Your mobile not corrct")]
        [RegularExpression("([1-9][0-9]*)", ErrorMessage = "You have to enter only numbers 111-111-1111")]
        [Required]
        [Remote("IsUserNameAvailabe","Account",ErrorMessage ="The mobile already in use")]
        public string Mobile { get; set; }

        [Required]
        [DataType("Password")]
        public string Password { get; set; }

        [Required]
        [DisplayName("First Name")]

        public string FirstName { get; set; }

        [DisplayName("Created Date")]
        public Nullable<System.DateTime> CreatedDate { get; set; }


    }
}


=====================================================

[HttpPost]
public ActionResult Register(string Mobile, string Password, string FirstName, int Disability)
{
ParkingContext db = new ParkingContext();

ParkingMvcApp.Models.Client client = new Models.Client();
client.Mobile = Mobile;
client.Role = "C";
client.Password = Password;
client.FirstName = FirstName;
client.CreatedDate = DateTime.Now;
client.TyepOfClientID = Disability;

//To check if the user already regitser
if (db.Clients.Any(m => m.Mobile == Mobile))
{
ModelState.AddModelError("Mobile", "The mobile already in use");
}

if (ModelState.IsValid)
{
db.Clients.Add(client);
db.SaveChanges(); <-----------------------------------Error
return RedirectToAction("Login", "Account");
}

return View(); ;

}

Note: If I remove the compare from the code , the program work as I expected
Posted
Updated 25-Jun-16 3:54am

Your approach is wrong here. Don't change your Data Model /Domain Model for View, you have yo create a ViewModel here and map those to DataModel, in View bind it to ViewModel and for DB Operartions use your DataModel.

You should not use Domain/ Data Model which is mapped to database table in View, you should use ViewModel according to requirements in your View and appply Compare, Required etc attributes on ViewModel, not Domain Model. I hope it helps.


C#
public class ClientVM
    {
        [StringLength(10, MinimumLength = 10, ErrorMessage = "Your mobile not corrct")]
        [RegularExpression("([1-9][0-9]*)", ErrorMessage = "You have to enter only numbers 111-111-1111")]
        [Required]
        [Remote("IsUserNameAvailabe","Account",ErrorMessage ="The mobile already in use")]
        public string Mobile { get; set; }
 
        [Required]
        [DataType("Password")]
        public string Password { get; set; }

        [DataType("Password")]
        [System.Web.Mvc.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
 
        [Required]
        [DisplayName("First Name")]
 
        public string FirstName { get; set; }
 
        [DisplayName("Created Date")]
        public Nullable<system.datetime> CreatedDate { get; set; }
        
    }
</system.datetime>



and your Model should be as per table in your Database:

C#
public class Client
    {
              
        public string Mobile { get; set; }

        public string Password { get; set; }

        public string FirstName { get; set; }

        public Nullable<System.DateTime> CreatedDate { get; set; }

    }




and your DataModel will remain same as per Table Mapping. For mapping ViewModel and Model you can see this article
 
Share this answer
 
v2
Comments
Member 11232188 22-Sep-15 10:28am    
this is my model

//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
//
//------------------------------------------------------------------------------

namespace ParkingMvcApp.Models
{
using System;
using System.Collections.Generic;

public partial class Client
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Client()
{
this.Cars = new HashSet<car>();
}

public string Mobile { get; set; }
public string Role { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public Nullable<system.datetime> BirthDate { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public Nullable<system.datetime> CreatedDate { get; set; }
public Nullable<system.datetime> LastLogin { get; set; }
public string Qusetion { get; set; }
public string Answer { get; set; }
public Nullable<int> TyepOfClientID { get; set; }

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<car> Cars { get; set; }
public virtual TypesofClient tblTypesofClient { get; set; }
}
}
Member 11232188 22-Sep-15 10:29am    
I do not know what I should change
Ehsan Sajjad 22-Sep-15 13:23pm    
You have to create a new class with properties that you need to use in View which is called ViewModel and when it is posted in action map it's properties to your geenrated model Client class before doing DB operations, so your DataBase Model and View Model will be different.
Member 11232188 22-Sep-15 16:33pm    
My question is:
When I remove the compare from my code the program work as I expect
Member 11232188 22-Sep-15 23:16pm    
Thanks
Add this line to your view
@Html.HiddenFor(model => model.ConfirmPassword)

and this to your action method in controller
C#
[HttpPost]
        public ActionResult Create(User user)
        {
            // TODO: Add insert logic here
            if (ModelState.IsValid)
            {
                user.ConfirmPassword = user.Password;
}
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900