0

What is the best way to avoid duplicate entries with MVC-EFC and ErrorMessage return

Model 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; }
}

I use a ApiController with "ErrorMessage" return. For column "Name" i do not want duplicates and a ErrorMessage return like "Entry already available!" What is the best way?

1
  • if you are looking to add something within the class, note that all the above validation are done on the client and web server, without hitting the db. Duplication check will need it to hit the db. I don't see how it can be done within a class Aug 26, 2018 at 5:10

1 Answer 1

0

Try to implement custom ValidationAttribute

  1. Customer 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. Use

    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; }
     }
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.