C# 字符串.empty上的EF6 ValidationErrors
我有一个配置文件类,我正试图保存到数据库(MS SQL)。在数据库中,字段列为“NOTNULL”。默认/初始条目将是空字符串(string.empty) 我认为空字符串对于NULL不会失败,但似乎EF正试图将它们作为NULL传递。是这样吗 下面是一些模型类:C# 字符串.empty上的EF6 ValidationErrors,c#,entity-framework-6,C#,Entity Framework 6,我有一个配置文件类,我正试图保存到数据库(MS SQL)。在数据库中,字段列为“NOTNULL”。默认/初始条目将是空字符串(string.empty) 我认为空字符串对于NULL不会失败,但似乎EF正试图将它们作为NULL传递。是这样吗 下面是一些模型类: [Required] public string Password { get; set; } public string PasswordSalt { get; set; } [Required] [Display(Name = "S
[Required]
public string Password { get; set; }
public string PasswordSalt { get; set; }
[Required]
[Display(Name = "Security Question")]
public string SecurityQuestion { get; set; }
[Required]
[Display(Name = "Security Answer")]
public string SecurityAnswer { get; set; }
这就是模型。下面是尝试使用r作为DataRow设置数据的代码:
newProfile = new Profile
{
Salutation = r["Salutation"].ToString(),
FirstName = r["FirstName"].ToString(),
MiddleName = r["MiddleName"].ToString(),
LastName = r["LastName"].ToString(),
Biography = r["Biography"].ToString(),
Password = string.Empty,
PasswordSalt = string.Empty,
SecurityQuestion = string.Empty,
SecurityAnswer = string.Empty,
EnteredDate = DateTime.Now,
LastUpdatedDate = DateTime.Now,
RecordVersion = StaticTools.RecordVersion(),
};
_db.Profile.Add(newProfile);
try
{
_db.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
因此,当我们尝试SaveChanges()时,它会失败,出现一个DbValidationError,用于密码、SecurityQuestion、SecurityAnswer
“安全问题字段是必需的。”
(当然,我们甚至不会检查登录时的空密码,用户必须遵循注册电子邮件并设置一个。)您的安全问题/答案属性上有“必需”标记。Required必须不是空字符串才能通过所需检查
删除[必需的]
标记,这将缓解您当前的问题
从
RequiredAttribute属性指定在验证表单上的字段时,该字段必须包含一个值。如果属性为null、包含空字符串(“”)或仅包含空格字符,则引发验证异常
默认情况下,
RequiredAttribute
不允许空字符串。通过将属性设置为true,可以覆盖此行为
[Required(AllowEmptyStrings = true)]
public string Password { get; set; }
public string PasswordSalt { get; set; }
[Required(AllowEmptyStrings = true)]
[Display(Name = "Security Question")]
public string SecurityQuestion { get; set; }
[Required(AllowEmptyStrings = true)]
[Display(Name = "Security Answer")]
public string SecurityAnswer { get; set; }
顺便说一下,考虑<代码>抛出<代码> VS代码>抛出EX/CODE >