public class ValidateProductCode:ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { // Declare and instantiate new DatabaseContext var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>(); optionsBuilder.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=MvcCompanyDB;Trusted_Connection=true;"); using var context = new DatabaseContext(optionsBuilder.Options); // Cast ValidationContext to ProductViewModel var model = (ProductViewModel)validationContext.ObjectInstance; // Declare and populate list of all Product's codes from database List<string> codeList = context.Products.Select(e => e.Code).ToList(); // Check if the value is not null or empty string if(value!=null && value.ToString() != string.Empty) { // Declare string variable and assign it's value to values's string string code = value.ToString(); // If model's Id is grater than 0 it means that ProductViewModel is used in Update operation if (model.Id > 0) { // Find product record by model's Id Products productsItem = context.Products.Find(model.Id); // If code is modified if (model.Code != productsItem.Code) { // If supplied code is already associated with any product in database then return error message if (codeList.Contains(code)) { return new ValidationResult("There is already product in database that has this code. Please provide different code!"); } // Otherwise retutn success else { return ValidationResult.Success; } } // Otherwise retutn success else { return ValidationResult.Success; } } // otherwise it is used in create operation else { // If supplied code is already associated with any product in database then return error message if (codeList.Contains(code)) { return new ValidationResult("There is already product in database that has this code. Please provide different code!"); } // Otherwise retutn success else { return ValidationResult.Success; } } } // Otherwise return error message else { return new ValidationResult("Please provide product code!"); } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)