实体框架核心没有与ErrorMessage重复的条目

时间:2018-08-25 11:53:41

标签: asp.net-core ef-core-2.1

避免MVC-EFC和ErrorMessage返回的重复条目的最佳方法是什么

Test.cs模型

public class Test
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Select a Name")]
    [StringLength(50, ErrorMessage = "Max 50 character")]
    public string Name { get; set; }

    [StringLength(100, ErrorMessage = "Max 100 character")]
    public string Text { get; set; }
}

我使用带有“ ErrorMessage”返回的ApiController。 对于“名称”列,我不希望重复,并且ErrorMessage返回如“条目已可用!” 最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

尝试实现自定义ValidationAttribute

  1. 客户ValidationAttribute

    public class UniqueValidation : ValidationAttribute
    {
    private readonly string _errorMessage;
    public UniqueValidation(string ErrorMessage)
    {
        _errorMessage = ErrorMessage;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext != null && typeof(IName).IsAssignableFrom(validationContext.ObjectType))
        {
            ApplicationDbContext db = validationContext.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
            IQueryable<IName> result = db.GetType().GetMethod("Set").MakeGenericMethod(validationContext.ObjectType).Invoke(db, null) as IQueryable<IName>;
            var v = result.FirstOrDefault(u => u.Name == ((IName)validationContext.ObjectInstance).Name);
            if (v != null)
            {
                return new ValidationResult(_errorMessage);
            }
        }
        return ValidationResult.Success;
    }
     }
    
  2. 使用

    public class File: IName
    {
    public int Id { get; set; }
    [UniqueValidation("FileName is exist")]
    public string Name { get; set; }
    [InverseProperty("Avatar")]
    public ICollection<ApplicationUser> Users { get; set; }
    }
    
    public interface IName
     {
    string Name { get; set; }
     }