Chapter 7. Customizing Validations
In the previous chapter you learned many ways that you can apply
validation rules so that the DbContext Validation API can find and check
them either on demand or automatically. While you can explicitly validate
individual classes and properties directly from the DbEntityEntry
method, you can also have the
context validate all of its tracked entities as a group, either by calling
GetValidationErrors
or letting SaveChanges
call that method for you. GetValidationErrors
then calls ValidateEntity
on each of the Added
and Modified
entities in the context. ValidateEntity
then triggers logic that checks the
ValidationAttribute
and IValidatableObject
rules you’ve specified in your
classes.
You’ve seen how ValidateEntity
works in Chapter 6. In this
chapter, you’ll learn how to customize the ValidateEntity
method not only by overriding the
logic of the method, but also by overriding the method that determines which
entities should be validated.
Overriding ValidateEntity in the DbContext
ValidateEntity
is a virtual
method, meaning that you can override it and add your own custom logic.
Like any virtual method, after executing your logic, you can control
whether or not it performs the validations it’s designed to execute (for
example, validating the ValidationAttribute
s and IValidatableObject
rules).
Example 7-1 shows the
ValidateEntity
method added into the
BreakAwayContext
class after using the
Visual Studio IDE shortcut to add the overridden method.
Get Programming Entity Framework: DbContext now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.