我有一个与验证属性相关的问题!我使用.net core 2.1。我在DbContext类的OnModelCreating方法中检查了唯一字段,它工作正常。现在,如果用户在诸如Display&Required&MaxLength&...属性之类的输入字段中输入相同的BirthCertificate值(数据库中已经存在),我想显示一条错误消息,并将其发送(绑定)到ModelState进行检查。我还在客户端中使用jquery.validate.js并显示所有错误,并且工作正常。我应该怎么做:
Public Class Person
{
[Display(Name = "Enter BirthCertificate")]
[Required(ErrorMessage = "Please enter {0}")]
[MaxLength(10, ErrorMessage = "Max lenght is {0}")]
public string BirthCertificate { get; set; }
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<DomainClasses.Person.Person>(entity =>
{
entity.HasIndex(e => e.BirthCertificate).IsUnique(); // it's working fine
});
}
谢谢
您可以使用其中之一。
1)在SQL Server中为BirthCertificate创建新的唯一密钥。使用catch(异常例外)并返回到ajax以显示错误。
2)检查代码
if (db.Person.Where(x => x.BirthCertificate.Contains(birthcert)).Any())
{
//return to ajax to show error
}