Adding Validation MetaData to Entity Framework Auto Generated Classes

Entity Framework’s Code First is one of my favorite tools, but in my experience it is somewhat uncommon…

Entity Framework’s Code First is one of my favorite tools, but in my experience it is somewhat uncommon to build a database from scratch. More often you are accessing and editing data in an existing database, or modifying its schema. Thankfully, Entity Framework 6.1 introduced “reverse code first”, which is more officially known as “Code First From Database”. This pattern allows you to choose an existing database, and Entity Framework will generate the appropriate entities and DbContext classes for it. This can also be a great option if you are a fan of code first syntax but still prefer to design your databases through SQL or Management Studio.

When you first start using Code First From Database, however, it won’t be long until you run into a problem. The framework generates correct entity classes for you based on your database tables, but what happens when you want to add additional meta data to these classes? Maybe you want to enforce certain model validation rules that don’t actually exist in the database. How do we add this meta data? Sure, you can add them directly to the classes Entity Framework generates, but if the database changes and you need to regenerate the classes, you’ll loose these updates. There must be a better way!

Thankfully there is. Entity Framework understands this issue, and so it generates all of its model classes as partial classes. This allows you to create a partial class of the same name and apply an attribute that tells the framework what class to use for additional meta data. Let’s see how this works. For this example I’m using the Northwind sample database from codeplex, which can be found here.

After you restore the databsae to your local Sql Server you can reverse engineer it into your project using Visual Studio.  We aren’t going to cover this in detail since the article focuses on meta data.  Some basic steps are below, skip them if you already know the process.

  • Right click on your project and choose “Add New Item”
  • Under the “Data” category on the left, choose ADO.NET Entity Data Model. Give the item a name like “NorthWindContext” and add it to your project.
  • On the next dialog, choose Code First From Database
  • Next you”l need to enter in the connection to your database
  • On the final screen, choose to import as many tables as you want

Adding Validation MetaData to Your Classes

We are going to add some validation rules to the employee class from the Northwind database.  We are going to make the Title and Region properties required.  There are really only three steps to get this all to work:

Step 1: Create a partial class to map the meta data

Remember, Entity Framework generates partial classes.  We can add information to them by adding our own partial class of the same name.   Right click the folder where your employee class is located and add another class called EmployeeMap.  After you create the file make sure to rename the actual class to Employee so it works as a partial class, as seen below.  Also make sure to add the MetadataType attribute to your partial class, and pass in the name of the additional class that will contain all of your additional validation rules.  We’ll call it EmployeeMeta.  That’s all we need from this class! It doesn’t even need any members. Now when Entity Framework regenerates any of our entities, this one will be left untouched.

    public partial class Employee

Next we need to add another class – this will be the EmployeeMeta class we specified before. You can either right click and add it through the Visual Studio menu or have it autogenerated using the CTRL P short cut on the class name you passed into the attribute.

public class EmployeeMeta

Finally, in the EmployeeMeta class, all we have to do is add properties with the same name as the ones Entity Framework generated, and apply our new rules to those.

public class EmployeeMeta
        public string Title { get; set; }
        public string Region { get; set; }

These rules will now be enforced in our project, and are safe from being erased when we regenerate the classes! That’s really all there is to it.

You May Also Like
Read More

HTTP Logging in ASP.NET 6.0

ASP.NET 6.0 is finally here! Don't let smaller features like HTTP Logging get lost in the hype - sometimes they add the most value to real development.