Exclude property of model in insert Entity Framework

asp.net-mvc entity-framework-6

Question

I get an error when inserting data into my database. My database columns are:

username, password 

and I added confirmpassword to the model to extend it.

How do I get rid of the confirmpassword to insert the username and password while using the model with confirmpassword property?

My code:

BootstrapTrainingEntities db = new BootstrapTrainingEntities();

var u = new User();

u.username = user.username;
u.password = user.password;
// how to I remove or ignore the confirmPassword property when saving?

db.Users.Add(u);
db.SaveChanges();

Model

[MetadataType(typeof(metadataUser))]
public partial class User
{
    public string confirmPassword { get; set; }
}

public class metadataUser
{
    [Required(ErrorMessage = "Username is required", AllowEmptyStrings = false)]
    [Display(Name ="Username")]
    public string username { get; set; }

    [Required(ErrorMessage ="Password is required", AllowEmptyStrings = false)]
    [Display(Name = "Password")]
    [DataType(DataType.Password)]
    public string password { get; set; }

    [Required(ErrorMessage ="Confirmation Password is required", AllowEmptyStrings = false)]
    [Display(Name ="Confiramation Password")]
    [DataType(DataType.Password)]
    [Compare("password",ErrorMessage = "Password does not match")]
    public string confirmPassword { get; set; }
}
1
0
5/18/2018 5:10:21 PM

Popular Answer

I think what you need to do is add a viewmodel for the page.First of all you will have model that is generated from entity framework which might look as below.

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

    public string username {get;set;}

    public string password {get;set;}
}

So now create a viewModel for your View .This might look as below.

public class UserViewModel
{
   public int id{get;set;}

   [Required(ErrorMessage = "Username is required", AllowEmptyStrings = false)]
   [Display(Name ="Username")]
   public string username { get; set; }

   [Required(ErrorMessage ="Password is required", AllowEmptyStrings = false)]
   [Display(Name = "Password")]
   [DataType(DataType.Password)]
   public string password { get; set; }

   [Required(ErrorMessage ="Confirmation Password is required", AllowEmptyStrings = false)]
   [Display(Name ="Confiramation Password")]
   [DataType(DataType.Password)]
   [Compare("password",ErrorMessage = "Password does not match")]
   public string confirmPassword { get; set; }
}

and now in your controller action method. you can do as below.

[HttpPost]
public ActionResult AddUser(UserViewModel model)
{
    User user=new User();
    user.username=model.username;
    user.password=model.password;
    db.User.Add(user);
}

Hope it helps !

2
5/18/2018 5:52:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow