我如何显示内核中唯一字段的错误 asp.net



我有一个与验证属性相关的问题!我使用 .net 核心 2.1。我在 DbContext 类中检查了 OnModelCreate 方法中的唯一字段,它工作正常。现在,如果用户在输入字段中输入相同的出生证明值(数据库中已存在(,我想显示一条错误消息,例如显示和必需和最大长度和...属性并将其发送(绑定(到 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 中为出生证明创建新的唯一密钥。使用 catch(异常 ex(并返回到 ajax 以显示错误。

2(做检查代码

if (db.Person.Where(x => x.BirthCertificate.Contains(birthcert)).Any())
{
//return to ajax to show error
}

最新更新