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

Disable Entity Framework validation for some specific field on insertion action

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

1
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.

我的模特课:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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; }
}

我的控制器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[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();
}

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


方法1:

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

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

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-实体框架在asp-net-mvc应用程序中,您可以在EF项目上启用代码迁移(假设您还没有这样做)。在使迁移满意后,编辑生成的迁移以允许密码中的空值。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);

它不是实体框架本身的问题。

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

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