Disable Entity Framework validation for some specific field on insertion action

asp.net-mvc asp.net-mvc-5 c# entity-framework entity-framework-6

Question

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.

1
0
9/9/2017 10:28:40 AM

Popular Answer

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://docs.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);
1
9/9/2017 11:10:04 AM


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