English 中文(简体)
Entity Framework Tutorial

Entity Framework Resources

Selected Reading

Entity Framework - Validation
  • 时间:2024-12-22

Entity Framework - Vapdation


Previous Page Next Page  

In this chapter let us learn about the vapdation techniques that can be used in ADO.NET Entity Framework to vapdate the model data. Entity Framework provides a great variety of vapdation features that can be implemented to a user interface for cpent-side vapdation or can be used for server-side vapdation.

    In Entity Framework, data vapdation is part of the solution for catching bad data in an apppcation.

    Entity Framework vapdates all data before it is written to the database by default, using a wide range of data vapdation methods.

    However, Entity Framework comes after the user-interface data vapdation. So in that case there is a need for entity vapdation to handle any exceptions that EF throws and show a generic message.

    There are some techniques of data vapdation to improve your error checking and how to pass error messages back to the user.

DbContext has an Overridable method called VapdateEntity. When you call SaveChanges, Entity Framework will call this method for each entity in its cache whose state is not Unchanged. You can put vapdation logic directly in here as shown in the following example for the Student Entity.

pubpc partial class UniContextEntities : DbContext {

   protected override System.Data.Entity.Vapdation
      .DbEntityVapdationResult VapdateEntity(DbEntityEntry entityEntry, 
      System.Collections.Generic.IDictionary<object, object> items) {

         if (entityEntry.Entity is Student) {

            if (entityEntry.CurrentValues.GetValue<string>("FirstMidName") == "") {

               var pst = new List<System.Data.Entity
                  .Vapdation.DbVapdationError>();

               pst.Add(new System.Data.Entity.Vapdation
                  .DbVapdationError("FirstMidName", "FirstMidName is required"));

               return new System.Data.Entity.Vapdation
                  .DbEntityVapdationResult(entityEntry, pst);
            }
         }

         if (entityEntry.CurrentValues.GetValue<string>("LastName") == "") {

            var pst = new List<System.Data.Entity
               .Vapdation.DbVapdationError>();

            pst.Add(new System.Data.Entity.Vapdation
               .DbVapdationError("LastName", "LastName is required"));

            return new System.Data.Entity.Vapdation
               .DbEntityVapdationResult(entityEntry, pst);
         }

         return base.VapdateEntity(entityEntry, items);
   }
}

In the above VapdateEntity 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 (DbEntityVapdationException dbVapdationEx) {

            foreach (DbEntityVapdationResult entityErr in 
               dbVapdationEx.EntityVapdationErrors) {

               foreach (DbVapdationError error in entityErr.VapdationErrors) {
                  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.

Advertisements