O'Reilly logo

Programming Entity Framework: DbContext by Rowan Miller, Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Considering Different Ways to Leverage ValidateEntity

In the previous example, ValidateEntity executes our context-based business validations. If no errors are found, it continues on to execute the base ValidateEntity method, which checks any rules defined with type validation (IValidatableObject rules) and property validation (ValidateAttribute rules). That’s just one execution path you could set up in ValidateEntity.

Note

Throughout this chapter, we’ll present different forms of the ValidateEntity method. If you are following along with the code samples, you might want to retain each version of ValidateEntity in the BreakAwayContext class. What we did while developing our samples was to wrap a complier directive around the methods that we don’t want to use anymore. This is cleaner than commenting out code. In C# you can add #if false before the beginning of the method and then #endif after the end of the method.

#if false
protected override DbEntityValidationResult
 ValidateEntity(DbEntityEntry entityEntry,
                IDictionary<object, object> items)
{
   ...method code
}
#endif

The code inside the directive will be grayed out and ignored by the compiler. Change the directive to #if true to reengage it.

In Visual Basic the directive looks like this:

#If False Then
#End If

You could reverse this logic, returning the base ValidateEntity results first and, if there are none, executing your custom logic as visualized in Figure 7-2.

Figure 7-2. Calling custom validation only if base validation finds on ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required