- Entity Framework Tutorial
- Entity Framework - Home
- Entity Framework - Overview
- Entity Framework - Architecture
- Entity F - Environment Setup
- Entity Framework - Database Setup
- Entity Framework - Data Model
- Entity Framework - DbContext
- Entity Framework - Types
- Entity Framework - Relationships
- Entity Framework - Lifecycle
- Entity F - Code First Approach
- Entity F - Model First Approach
- Entity F - Database First Approach
- Entity Framework - DEV Approaches
- Entity F - Database Operations
- Entity Framework - Concurrency
- Entity Framework - Transaction
- Entity Framework - Views
- Entity Framework - Index
- Entity F - Stored Procedures
- Entity F - Disconnected Entities
- Entity F - Table-Valued Function
- Entity Framework - Native SQL
- Entity Framework - Enum Support
- Entity F - Asynchronous Query
- Entity Framework - Persistence
- Entity F - Projection Queries
- Entity F - Command Logging
- Entity F - Command Interception
- Entity Framework - Spatial Data Type
- Entity Framework - Inheritance
- Entity Framework - Migration
- Entity Framework - Eager Loading
- Entity Framework - Lazy Loading
- Entity Framework - Explicit Loading
- Entity Framework - Validation
- Entity Framework - Track Changes
- Entity Framework - Colored Entities
- Entity F - Code First Approach
- Entity Framework - First Example
- Entity Framework - Data Annotations
- Entity Framework - Fluent API
- Entity Framework - Seed Database
- Entity F - Code First Migration
- Entity F - Multiple DbContext
- Entity F - Nested Entity Types
- Entity Framework Resources
- Entity Framework - Quick Guide
- Entity Framework - Useful Resources
- Entity Framework - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Entity Framework - Validation
In this chapter let us learn about the validation techniques that can be used in ADO.NET Entity Framework to validate the model data. Entity Framework provides a great variety of validation features that can be implemented to a user interface for client-side validation or can be used for server-side validation.
In Entity Framework, data validation is part of the solution for catching bad data in an application.
Entity Framework validates all data before it is written to the database by default, using a wide range of data validation methods.
However, Entity Framework comes after the user-interface data validation. So in that case there is a need for entity validation to handle any exceptions that EF throws and show a generic message.
There are some techniques of data validation to improve your error checking and how to pass error messages back to the user.
DbContext has an Overridable method called ValidateEntity. When you call SaveChanges, Entity Framework will call this method for each entity in its cache whose state is not Unchanged. You can put validation logic directly in here as shown in the following example for the Student Entity.
public partial class UniContextEntities : DbContext { protected override System.Data.Entity.Validation .DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, System.Collections.Generic.IDictionary<object, object> items) { if (entityEntry.Entity is Student) { if (entityEntry.CurrentValues.GetValue<string>("FirstMidName") == "") { var list = new List<System.Data.Entity .Validation.DbValidationError>(); list.Add(new System.Data.Entity.Validation .DbValidationError("FirstMidName", "FirstMidName is required")); return new System.Data.Entity.Validation .DbEntityValidationResult(entityEntry, list); } } if (entityEntry.CurrentValues.GetValue<string>("LastName") == "") { var list = new List<System.Data.Entity .Validation.DbValidationError>(); list.Add(new System.Data.Entity.Validation .DbValidationError("LastName", "LastName is required")); return new System.Data.Entity.Validation .DbEntityValidationResult(entityEntry, list); } return base.ValidateEntity(entityEntry, items); } }
In the above ValidateEntity method, Student entity FirstMidName and LastName properties are checked if any of these property have an empty string, then it will return an error message.
Let’s take a look at a simple example in which a new student is created, but the student’s FirstMidName is empty string as shown in the following code.
class Program { static void Main(string[] args) { using (var context = new UniContextEntities()) { Console.WriteLine("Adding new Student to the database"); Console.WriteLine(); try { context.Students.Add(new Student() { FirstMidName = "", LastName = "Upston" }); context.SaveChanges(); } catch (DbEntityValidationException dbValidationEx) { foreach (DbEntityValidationResult entityErr in dbValidationEx.EntityValidationErrors) { foreach (DbValidationError error in entityErr.ValidationErrors) { Console.WriteLine("Error: {0}",error.ErrorMessage); } } } Console.ReadKey(); } } }
When the above example is compiled and executed, you will receive the following error message on the console window.
Adding new Student to the database Error: FirstMidName is required
We recommend you to execute the above example in a step-by-step manner for better understanding.