private ValidationResult ViewModelValid(object value, ValidationContext validationContext) { using (var db = new AppDbContext()) { var Name = TargetPropertyName; PropertyInfo IdProp = TargetModelType.GetProperties().FirstOrDefault(x => x.CustomAttributes.Count(a => a.AttributeType == typeof(KeyAttribute)) > 0) ?? TargetModelType.GetProperties().FirstOrDefault(); int Id = (int)validationContext.ObjectInstance.GetType().GetProperty(IdProp.Name).GetValue(validationContext.ObjectInstance, null); //int Id = (int)IdProp.GetValue(validationContext.ObjectInstance, null); Type entityType = TargetModelType; var result = db.Set(entityType).Where(Name + "==@0", value); int count = 0; if (Id > 0) { result = result.Where(IdProp.Name + "<>@0", Id); } count = result.Count(); if (count == 0) { return(ValidationResult.Success); } else { return(new ValidationResult(ErrorMessageString)); } } }
private ValidationResult ViewModelValid(object value, ValidationContext validationContext) { if (validationContext.ObjectType.FullName == "SSProductCatalogWebApp.Models.EditProductViewModels") { return(ValidationResult.Success); } else { using (ProductCatalogEntities db = new ProductCatalogEntities()) { var Name = TargetPropertyName; PropertyInfo IdProp = TargetModelType.GetProperties()[1]; var code = validationContext.ObjectInstance.GetType().GetProperty(IdProp.Name).GetValue(validationContext.ObjectInstance, null); Type entityType = TargetModelType; var result = db.Set(entityType).Where(Name + "==@0", value); int count = 0; if (code != null) { result = result.Where(IdProp.Name + "==@0", code); } count = result.Count(); if (count > 0) { return(new ValidationResult(ErrorMessageString)); } else { return(ValidationResult.Success); } } } }