Entity Framework using Partial classes to add business logic and validation to generated entities

With Entity Framework you can use partial classes and partial methods to add business logic or override certain methods of the generated Entity Framework entities. You can find the default MSDN information about partial classes here :
http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.80).aspx

In my project I have a ADO.NET Entity Data Model which looks as following:

Entity Framework ADO.NET Entity Data Model

If we look at the generated entity code for the entity Post in the designer code:

Entity Framework partial entities

You can notice the class Post is marked with the partial keyword. This allows you to attach code to this generated class. If you would add code to this generated entity directly into the generated code, the next time you update the ADO.NET Entity Data Model, you would lose the changes you made, since it is generated code. To add Methods to the Post class that can persist, even if you update the model, you can make use of partial classes.

Entity Framework partial classes adding code to entity

In the same library as which your ADO.NET Entity Data Model belongs to, you can create a partial class Post. It is important that the partial class Post belongs to the same namepace as the partial class Post that is generated in the designer of the model. At runtime, the class is being constructed with the results of both these 2 partial classes into 1 single class.

In our partial class we created, we added for example a business logic operation WritePost() which in our case simply writes the output of the variables of the class to the output window. Notice that even though the _Title and _Id properties are not defined in my partial class I created, they are accessible to this partial class since those properties are defined to the other partial class that was generated. That means in the newly created partial class you can add logic that works on properties and variables defined in the other partial class.

If we write some code to test this behavior:

Entity Framework partial classes

By default the WritePost method is not defined in our generated entity, but by adding a partial class to our project with the same name and namespace, we are able to add custom logic to our generated entity. Next time you update the ADO.NET Entity Data Model, your changes will persist.

Executing the console application behaves as expected:

Entity Framework partial classes

If you look into the generated entity code, you will also find partial methods back, on which you can attach logic:

Entity Framework partial classes

We have a OnTitleChanging(string value) partial operation. If for example we would to add some validation logic every time someone changes the Title of a Post entity, we could do with writing a partial operation in our partial class:

Entity Framework partial onChanging onChanged operations

If we now try to change the value of the Title property of a post entity in to a value that is less then 10 characters, a notification gets written to the output window:

Entity Framework partial classes

Result:

Entity Framework partial classes

Any suggestions, remarks or improvements are always welcome.
If you found this information useful, make sure to support me by leaving a comment.

Cheers and have fun,

Robbin

About these ads

8 comments on “Entity Framework using Partial classes to add business logic and validation to generated entities

  1. Great article! We are researching using the Entity Framework at my work and are debating the best methods for integrating validation and business logic.

  2. I’m using visual studio 2012 and I see no OnChanging or OnChanged partial methods for any of the properties in the generated classes.

  3. Nice article! Together with extra properties added to this partial class, we can have a transparent encryption done at entity level. LINQ query can be working, too! This solves our problems in terms of security enhancement!

  4. If you have generated the model using EF5, then there is no need to include the model’s namespace in the file containing your partial class definitions. I struggled with this for a day, because all the articles showing this called for “using thenamespace” and wrapping the partials in a namespace thenamespace block. Simply not required in EF5

  5. Thanks for this post , but if we are using winform what i should do to popup a messagebox
    do i need to add an exception and how to call it from my form class ???
    and can i modify values in onchanging() function like:

    partial void OnEndDateChanging(DateTime? value)
    {
    if (this.StartDate >= this.EndDate)
    {
    this.EndDate = DateTime.Parse(“01/01/2012″);
    //this.EndDate = StructuralObject.SetValidValue(DateTime.Parse(“01/01/2010″), “EndDate”);
    //throw new Exception(“End Date should be greater than End Date”);
    }
    }
    Thank In Advance

  6. Thanks for the post, I am using partial classes in my project but when I run the code CreateObjectSet(MyEntity) throws an exception saying that my entity cant be found in the model. My partial class is wrapped in a namespace but if I try to remove the namespace then I get build errors cause it don’t know about MyEntity anymore. Could anyone lead me some assistance, I’d greatly appreciate it. I’m using EF 5, I have my context.tt and designer in one project and my generated entities in a Domain Class Library project, this is also where my partial class is.

    Thanks in advance.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s