Custom ValidationContext for EF?

2019-07-19 17:07发布

问题:

I'm using EF as my dataprovider to save and validate my items. I have some custom validation logic which needs access to other services or items. I know the ValidationContext class supplies these options. My question is how can I get my own validation context with an service provider or item to EF?

When I implement the IValidateObject interface on my POCO entity I get an instance of the validation context, but where can I make sure my own ValidationContext is used instead of the EF default one?

I want to base some validation on the fact that a service or item is available in the ValidationContext

回答1:

To pass the ValidationContext you need to override DbContext.ValidateEntity(). The method takes two parameters - entity entry and items. You would pass your validation context in the items dictionary. Take a look at this stackoverflow question.