Here's an example of a ValidateEntity override that validates new Posts to ensure that the post title hasn't been used already. You can put validation logic directly in here or even use this method to call, for example, the Blog.Validate method added in the previous section. When you call SaveChanges, Entity Framework will call this method for each entity in its cache whose state is not Unchanged. Because I set both property names in the ValidationResult, the MVC HtmlHelpers display the error message for both of those properties.ĭbContext has an overridable method called ValidateEntity. Unlike the validation provided by the Fluent API, this validation result will be recognized by the View and the exception handler that I used earlier to add the error into ModelState is unnecessary. Since this validation checks both the Title and the BloggerName, both property names are returned. The ValidationResult constructor takes a string that represents the error message and an array of strings that represent the member names that are associated with the validation. I'll demonstrate the validations with a simple pair of classes: Blog and Post. Additional validations, and more complex, can be specified in code and will work whether your model hails from code first, model first or database first. When using code first, you can specify validations using annotation or fluent API configurations. The content on this page is adapted from an article originally written by Julie Lerman ( ).Įntity Framework provides a great variety of validation features that can feed through to a user interface for client-side validation or be used for server-side validation. If you are using an earlier version, some or all of the information does not apply discussed in this page were introduced in Entity Framework 4.1. EF4.1 Onwards Only - The features, APIs, etc.
0 Comments
Leave a Reply. |