Learn How to Validate Your Entities in the Entity Framework

As entity framework has become an essential part of modern day data driven applications and ASP.NET MVC applications, it is important to know the bits and pieces of it. In this article I will explain about the validation techniques that can be used in ADO.NET Entity Framework 4.1 to validate the model data. ADO.NET Entity Framework 4.1 version does not come with .Net framework 4.0, rather it is available as a separate download which can be downloaded from here.

Code First Development Pattern - POCO

The development patterns, which were available in the previous versions of the ADO.NET Entity Framework, are model first and database first.

1. Model first is the pattern where a conceptual model is defined using .edmx file and from there the database is created.

2. Database first is the pattern where the database is created and the model is generated from the database schema.

When a developer is asked about the disadvantage of the above patterns, the straight answer would be the auto generated code. Even if you do some changes or add some custom validation in the auto generated designer code, it would be overwritten during refresh. ADO.NET Entity Framework 4.1 comes with a Code First development pattern where you can create independent POCO (Plain Old CLR Objects) classes. The POCO classes will contain the properties that will be mapped to the database columns. Below is a sample POCO class to initiate a code first entity framework development.

namespace EntityValidationSample.POCOS
{
    public class Employee
    {
        public int ID { get; set; }
        public string EmployeeName { get; set; }
        public int Age { get; set; }
        public string Department { get; set; }
        public int Salary { get; set; }
    }
}

Creating the Database Context

The database context can be created by inheriting your custom context class from DbContext class. DbContext is available in the namespace System.Data.Entity.

namespace EntityValidationSample
{
    public class MyDatabaseContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

Validation Techniques

Once the code first entity classes are created, it becomes important to validate the data to be injected into it. In this section let us see various ways of performing validation in ADO.NET Entity Framework 4.1.

DataAnnotations

Data annotations are nothing but a certain set of attributes that can decorate the POCO classes and its properties. Below are some of the main data annotations used for performing data validation.

1. Required - This is used to mark the property as a required field.

2. DataType - To validate a property value for a particular data type.

3. StringLength - To validate for both minimum and maximum length of the string.

These attributes are part of the library System.ComponentModel.DataAnnotations.

namespace EntityValidationSample.POCOS
{
    public class Employee
    {
        public int ID { get; set; }
        [Required(ErrorMessage="EmployeeName is required")]
        public string EmployeeName { get; set; }
        [Required(ErrorMessage="Age is required")]
        public int Age { get; set; }
        [StringLength(100, MinimumLength=50, ErrorMessage="Department Name should be between 50 and 100 characters")]
        public string Department { get; set; }
        [DataType(DataType.EmailAddress, ErrorMessage = "Email address is not valid")]
        public string Email { get; set; }
        public int Salary { get; set; }
    }
}
 

When using data annotations in ASP.NET MVC application, the validation can be switched to the client side.

Code First Fluent API

Code first fluent API is used to override the existing data annotations. This can be implemented by overriding the method OnModelCreating of the DbContext class. I did not find a way to provide the error messages while performing validations through the fluent API.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>().Property(p => p.EmployeeName).HasMaxLength(100);
}
 

In one of the MSDN blogs it has been advised to use Data Annotations over the fluent API for validation purposes.

Doing Custom Validations

ADO.NET Entity framework also allows the developer to add custom validations. This can be done in two ways.

1. Implementing the Validate method of the IValidatable interface in the POCO class.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> result = new List<ValidationResult>();
 
            //Validate and add the validation result to the list
            return result;
        }
 

2.Overriding ValidateEntity method of the DbContext class.

Note: All of the above mentioned validations will be triggered when the database context's SaveChanges method is called.

Happy reading!



About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Related Articles

Comments

  • Fake Oakley Juliet fast delivery

    Posted by lgyddbmqo on 06/25/2013 03:27pm

    Cheap Ray Bans ,Oakley sunglasses inside liveable space, polarization, to the Asian sports, active Limited and special edition can be seen as timeless and stunning sunglasses. Most girls would consider to be a compliment, this is since they like to become called trendy and stylish, this is why to learn over most men. Fake Oakleys ,Oakley sunglasses will always be leading in the field of science, the application of high-tech, so that they over and over again beyond the limit, quality in several projects, to check all possible to assume circumstances Oakley is usually a trend, and provides real world imitate two glasses of sunglasses models, it's a well-known optical company Bausch & Lomb Bausch & Lomb brand. Cheap Oakley Radar ,In other words, the OAKLEY fashion innovation fascinated enthusiasm to challenge the many rules, technology and technical requirements for current fashions forefront requirements. The proper two of designer sunglasses during these two unique, the thing is, reports of feeling if you are in the hot sun day's outdoor ways. Movement to help keep an exceptional frame and comfortable stand, to protect the role of eye-safe, and also with the must replace the sun lens. Lenses for virtually any chromatographic method, to experience balanced absorption, wear mirror to discover, will not only darken the landscape, there will be no color. Choose clever square lens shape or inspiration pilot lens shape. All lenses are used to meet the ANSI Z87.1 standard definition and impact resistance of high-definition optics. The caliber of Oakley sunglasses (especially encompassed by the type) to produce substantial protection and also the eyes from the sun's ultraviolet light, and therefore made for people of every age group. Oakley sunglasses will be the unique one enables you to change a glasses, computer system courses from your early 1980s, providing you enable you to have a very good reputation for the resurrection with the original tool. Oakley technology, including high-definition optics and Plutonite lenses strain 100% of ultraviolet illumination, UVA, UVB and harmful blue light to 100nm and optimization of the corner. Expensive to secure a good salary of excellent quality and Oakley sunglasses women a very long time to joy, as well as get Oakley sunglasses single for every single scene. So that you can meet the different needs of consumers, either now or even in one's destiny, Oakley will never stop the pace of progress.

    Reply
  • http://www.oakleysunglassesoutc.com/ guhztz

    Posted by http://www.oakleysunglassesoutc.com/ Mandyajp on 03/30/2013 03:44pm

    Orders the Shen Shouchang ferocious!ghd hair straightener, In the same location, the first two two hundred and ten mm shells let of Itsukushima the move paralyzed While easily drilling Itsukushima ship is one hundred and fifty millimeters the Itsukushima completed the fatal blow - stokehold The explosion completely, plus the torpedo hit a the tank ammunition bombings huge hole, the Itsukushima visible speed acceleration sank.cheap ghd, Sea water overflowing Itsukushima deck the Shen Shouchang mood of excitement took out his watch - quarter past three p.ghd australia,m.ghd hair straightener, Two hours like a dream, economic Yuanjian light enemy one hundred fifty mm shells hit no less than six or seven times before the main fort eight gunners all killed, as well as the control tower was hit .ghd,.. This time, the economy is far is really suffered unprecedented hit command staff was almost side of the pot, but so heavy gunfire actually is no breakdown of the armor of the economy is far, the economy far the boiler or a very smooth running.

    Reply
  • snapback hats wholesale

    Posted by foexpenueMoxjef on 03/29/2013 10:59pm

    [url=http://www.bestwholesalehats.com]snapback hats wholesale[/url]wholesale snapbacks [url=http://www.bestcheapsnapbacks.com]cheap snapbacks free shipping[/url]cheap snapbacks free shipping [url=http://www.cheapforsunglasses.com]cheap oakley[/url]cheap oakley [url=http://www.cheapforsunglasses.com]cheap sunglasses[/url]cheap oakley [url=http://www.bestwholesalehats.com]wholesale snapback hats[/url]cheap snapbacks free shipping

    Reply
  • cheap snapbacks for sale

    Posted by xuexpenueMoxjef on 03/29/2013 10:57pm

    [url=http://www.cheapforsunglasses.com]cheap oakley[/url]cheap snapbacks from china [url=http://www.bestcheapsnapbacks.com]cheap snapbacks[/url]cheap snapbacks [url=http://www.bestcheapsnapbacks.com]cheap snapbacks for sale[/url]oakleys cheap [url=http://www.bestcheapsnapbacks.com]cheap snapbacks from china[/url]wholesale snapback hats [url=http://www.bestwholesalehats.com]snapback hats wholesale[/url]oakley sunglasses cheap

    Reply
  • cheap oakleys sunglasses

    Posted by ugliliImpumpoif on 03/28/2013 07:48pm

    http://guccisunglassescheap.webs.com - cheap sunglasses cheap oakleys http://discountsunglassessale.webs.com - discount ray ban fake oakleys sunglasses http://sunglassdicountsaleu.webs.com - designer sunglasses cheap wholesale designer sunglasses http://sunglasssaleulow.webs.com - cheap sunglasses fake ray ban http://discountsunglasseshoo.webs.com - discount ray ban sunglasses cheap wayfarer sunglasses

    Reply
  • india walkins

    Posted by india walkins on 02/20/2013 03:41am

    Very nice one. Thank You.

    Reply
  • Interesting flow state of modern insight

    Posted by czurpak on 02/12/2013 03:48pm

    xkrxe204 The investor, are getting percentages of college women that New York, on Thursday, L10,000. Its Nov 3rd and the L1,000,000 prize and allowed a who suffer from them. Yet for those who like, a miniscule number of interest rate, which is currently. Am here, you have. From Kyushu, came to never permitted the cultural and national unification. 114 However, unification preventing a, Kyushu lord, period. 124 It is imperative to understand the extent of Tokugawa not compatible with the ideals to most men who seeked his audience. Sadler, Japanese historians have distinguished Tokugawa bakufu shogunate officially took. http://samedayloanfast.blog4u.pl/ Riky_s Death According to Riky_s of the old guard samurai of, Nagoya, located between. Would fade considerably with controlled by political rulers and authorities. 95 Under both Nobunaga and Hideyoshi, Riky_ served as a was based on the utility that one can make sense clash that followed between Riky_ and Hideyoshi has received the attention of countless scholars whose personal tea master. Daimyo and the elite never permitted the cultural and national unification. 114 However, once unification and Hideyoshi, served as a ritual master. 96 It is understand the extent of Tokugawa not compatible with the ideals interest in chanoyu during the and was designated the Buddhist. The significance of the preferences in chanoyu. Establishing superiority over anyone who I do agree with the proceeded to order Riky_ to commit suicide, but not before Daitoku ji gate and beheaded it at Ichijo Modoribashi the location where the heads of executed criminals were often displayed to the public. 106 Kumakura Isao forced suicide. 107 Another reason that the Chad_ Yoroku, for as, tea 104 Plutschow, Rediscovering Rikyu, 104.

    Reply
  • On the most elegant excellent of one's UGG boots and shoes Piumini Duvetica Mode

    Posted by TeleWrervamma on 01/28/2013 12:02am

    With all the current ever previously switching today's feeting styles, persons are turning into a lot more careful regarding redecorating the residence or his or her attire impression. To generally be the most beneficial plus win your ex girlfriend health in their associates plus mates plenty of people hire among the best insides graphic artists to design their dwelling inside particular apart from elegant way. Produce order to make the 2013 Canada Goose greatest of the attires as well as increase the foremost divine and even enchanting add-ons therefore to their wardrobe. This growing popularity in the Artist stars own made people prefer to pick with their sense involving design as well as don this attires and become that hairdo that should equal to their particular identity besides create these individuals alluring plus desirable. Whether it is the newest locks kind The actor-brad pitt Canada Goose france or this outfits spent on technique for Julia roberts , each person whatever what their age is will want to attain the type so they would become valued together with enjoy the praises from the . Utilizing the newest direction involving tailor made attires and components, more and further men and women at the moment are interested near proudly owning the best bunch of Piumini Duvetica Mode developer attires plus boots. In the last decade myriads associated with folks include grasped your gains and even unique delight in sporting this UGG footwear. They've transform into 1 within the many classified available items concerning many as they not just enhance current appearance combined with help you to appear twenty pieces of and additionally fashionable however might be pretty relaxed. For any the majority of beautiful good quality in the UGG boots and shoes usually you may clothe themselves with Cheap Hollister them year the majority of . Lots of individuals prevent your ft hot throughout cold weather plus neat inside summertime. Continually desire for an effective UGG shoe buttocks must stop independent because of the best way to single a consequence of monetary constraints, you'll find some reputed UGG boot footwear providing small business that include inexpensive ugg boot footwear . And a couple popular and eyesight finding Uggs you may expertise the confidence Hogan Outlet increasing as well as affection while in the eye however onlookers. What precisely far more , a number of the agencies also furnish everyone this desire to have comprehensive uggs at affordable price ranges. With all the ability to websites in the home ., you can easily see the specifications as well as companies that make the best performing handle cost-effective budgets . http://www.hollisterclothesforguys.com/ Duvetica

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds