对插入操作的某些特定字段禁用实体框架验证

时间:2017-09-09 04:56:30

标签: c# asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-6

我正在尝试在插入数据时禁用某些字段的验证,包括密码。但插入时出现以下错误:

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.

我的模特课:

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; }
}

我的控制器:

[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();
}

我真的很感激有人可以帮助我,告诉我哪里出错了。

2 个答案:

答案 0 :(得分:1)

实体框架本身不是问题。

您的表学生不接受 null 密码的学生。您可以为学生提供一些随机密码,也可以从用户输入中获取。

我建议将此列设为null。在我看来,我们不建议这样做。密码非常重要,将来可能会导致一些奇怪的行为。

答案 1 :(得分:1)

方法1:

如果查看SQL Server表本身,则需要密码字段。您可以在Visual Studio SQL Server对象资源管理器(在“视图”菜单下)或SQL Server Management Studio等工具中查看。您必须先设置此字段以允许空值,然后才能插入具有空密码的记录(请参阅下面的“允许空值”列,您必须在要允许空值的任何列中选中此框。 )

确保项目中的其他任何人都知道他们也需要进行此更改。

enter image description here

方法2:

使用Code First迁移。按照本指南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,您可以在EF项目上启用代码迁移(假设您还没有这样做)。在您的迁移满意后,编辑生成的迁移以允许密码中的空值。 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);