0

I'm trying to implement a custom validation attribute for unique records. For that I need to check the database, so I can notify user that given data already exists.

For that I need to access database inside of IsValid method of my Custom validation attribue:

public class CustomValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //This is always null
            var context = (DataContext)validationContext.GetService(typeof(DataContext));
            
        }
    }

I alredy tried to implement custom DataAnotation with DI acording to this post: stack overflow link

but it does not work. Maybe due to .net6 changes? I get error that EditContext cannot by changed dynamicaly.

Can some point me in the rigth direction please? Thank you.

1 Answer 1

1

Dependency Injection in ValidationAttributes should be available with .net7.0-preview1: https://github.com/dotnet/aspnetcore/pull/39445

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.