0

I am trying to disable validation of some field including password while inserting data. But I am getting the following error while inserting:

Cannot insert the value NULL into column 'Password', table 'Uni.Models.MyDb.dbo.Students'; column does not allow nulls. INSERT fails. The statement has been terminated.

My model class:

public class Student
{
    [Key]
    public int StudentId { get; set; }

    [Required(ErrorMessage = "Name Required")]
    public string Name { get; set; }

    public string IdNumber { get; set; }

    [Required(ErrorMessage = "Please Enter Password"), MinLength(5, ErrorMessage = "Password length error")]
    public string Password { get; set; }

    [Required, Compare("Password", ErrorMessage = "Invalid Confirm Password")]
    public string ConfirmPassword { get; set; }

    [Required(ErrorMessage = "Date Of Birth Required")]
    [Column(TypeName = "Date")]
    public DateTime BirthDate { get; set; }


    public virtual Gender Gender { get; set; }
    [Required(ErrorMessage = "Select Gender!")]
    public int GenderId { get; set; }
}

My controller:

[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public ActionResult add(Student std)
{
    db.Configuration.ValidateOnSaveEnabled = false;

    if (ModelState.IsValidField("Name") && ModelState.IsValidField("GenderId") && ModelState.IsValidField("BirthDate"))
    {
        Common common = new Common();
        std.IdNumber = common.generateUsername("S-");

        db.Students.Add(std);

        db.SaveChanges();
        db.Configuration.ValidateOnSaveEnabled = true;

        return RedirectToAction("Index");
    }

    ViewBag.Genders = new SelectList(db.Genders, "GenderId", "Dari");
    ViewBag.Provinces = new SelectList(db.Provinces, "ProvinceId", "Name");

    return View();
}

I really appreciate anyone could help me with this and tell me where am I going wrong.

SiHa
  • 7,830
  • 13
  • 34
  • 43
  • You could disable constraint check in DB. See [here](https://stackoverflow.com/a/737167/5045688). Of course, it is done differently in each database. – Alexander Petrov Sep 09 '17 at 08:16
  • If the `Password` is optional, then it should be nullable in your database. Setting `db.Configuration.ValidateOnSaveEnabled` won't change your database column constraint. – adiga Sep 09 '17 at 08:17
  • Also you should create a separate `StudentViewModel` and use it to submit the form. Put all your `Required` attributes in this class. Then in your controller, create an instance of `Student` class and populate it using the submitted `StudentViewModel` object. Mixing both will lead to problems like these. – adiga Sep 09 '17 at 08:19

2 Answers2

1

It is not a problem with entity framework itself.

Your table Students does not accept students with null password. You can make some random password for student or take it from user input.

I suggested also making this column null. Which is not advised in my opinion. Password are very important and it could lead to some weird behaviours in future.

Shoter
  • 976
  • 11
  • 23
  • db.Configuration.ValidateOnSaveEnabled = false; i used it to temporary disable validation – mostafa hakimi Sep 09 '17 at 05:02
  • But you are still not going to insert any data into table if your table does not accept nulls on password column. It just cannot store this kind of data. Maybe you will eliminate error but your code will stop working which is equivalent to having error. Either insert password randomly or by user input or allow nulls on this column. (Which would be very weird) – Shoter Sep 09 '17 at 05:04
  • My problem is not just with password field. suppose i am going to disable validation on gender. then what? – mostafa hakimi Sep 09 '17 at 05:05
  • Your error states that you are inserting record with null password. Try to check with debugger what values have your variables on line with db.Students.Add(std);. – Shoter Sep 09 '17 at 05:07
  • Thanks You are right, i am inserting null password but i have disabled validation with this (db.Configuration.ValidateOnSaveEnabled = false; ). this code works like a charm for editing but not for inserting. – mostafa hakimi Sep 09 '17 at 05:10
  • I would advise you to enable validation. You are inserting data into database which also have it's own validation. Validation ensures that you will insert correct data. And in mssql you will not insert incorrect data even if you disable validation. What's your error on editing? – Shoter Sep 09 '17 at 05:14
  • This is a big form in fact with many fields. a am creating a student and filling only some fields but the rest will be updated later by students themselves. – mostafa hakimi Sep 09 '17 at 05:22
1

Method 1:

If you look at the SQL server table itself, it requires the password field. You can view this in the Visual Studio SQL Server Object Explorer (Under the View menu), or in a tool like SQL Server Management Studio. You'll have to set this field to allow nulls before you can insert a record with a NULL password (see the Allow Nulls column below, you'll have to check this box in any column you want to allow nulls in)

Make sure that anyone else working on the project knows that they also need to make this change.

enter image description here


Method 2:

Use Code First migrations. Following this guide here https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application you can enable code migrations on your EF project (assuming you haven't done so already). Once you've enabled migrations to your satisfaction, edit the generated migration to allow nulls in Password. E.g:

CreateTable(
            "dbo.Students",
            c => new
                {
                    StudentId = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false),
                    IdNumber = c.String(),
                    Password = c.String(nullable: true), // This is the key bit - whether you set the value to nullable. The default is true, but because you marked the field as required nullable will be set to false
                    ConfirmPassword = c.String(nullable: true), // Same as above - by default this is required too. You might want to remove this property from your data object altogether
                    BirthDate = c.DateTime(nullable: false, storeType: "date"),
                    Gender = c.Int(nullable: false),
                    GenderId = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.StudentId);
marksfrancis
  • 1,722
  • 1
  • 13
  • 14