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

how i can Show error for unique fields in asp.net core

我有一个关于验证的问题属性!我使用 .net 核心 2.1。我在 DbContext class 的 OnModelCreating 方法中检查了唯一字段,它工作正常。现在我想显示一条错误消息,如果用户在输入字段中输入相同的 BirthCertificate 值(已存在于数据库中),例如 Display & Required & MaxLength & ... 属性并将其发送(绑定)到 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 服务器中为 BirthCertificate 创建新的唯一密钥。使用 catch (Exception ex) 和 return 到 ajax 来显示错误。

2) 检查代码

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