[英]EF6 ValidationErrors on string.empty
我有一个Profile类,我试图将其保存到数据库(MS SQL)。 在数据库中,这些字段被列为“ NOT NULL”。 默认/初始条目将是空字符串(string.empty)。
我认为空字符串不会因NULL而失败,但似乎EF试图将它们传递为NULL。 是这样吗
这是一些模型类:
[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()时,对于密码,SecurityQuestion,SecurityAnswer,它将失败,并出现DbValidationError。
“安全问题字段为必填。”
(当然,我们甚至不会检查登录密码是否为空,用户将必须遵循注册电子邮件并设置一个。)
默认情况下, RequiredAttribute
不允许空字符串。 您可以通过将AllowEmptyStrings
属性设置为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; }
您在安全性问题/答案属性上具有“必需”标签。 必需不需要为空字符串即可通过必需的检查。
删除[Required]
标签,这将缓解您的直接问题。
RequiredAttribute属性指定在验证表单上的字段时,该字段必须包含一个值。 如果属性为null,包含空字符串(“”)或仅包含空格字符,则会引发验证异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.