Click here to Skip to main content
15,881,455 members
Articles / Web Development / ASP.NET
Article

A Beginner's Tutorial on Performing Validations in Entity Framework using Partial Methods

Rate me:
Please Sign up or sign in to vote.
4.70/5 (8 votes)
6 Oct 2012CPOL4 min read 35.3K   745   33   2
This article talks about performing validations while using Entity framework. We will see how the Entities facilitate validations using partial methods.

Introduction

This article talks about performing validations while using Entity framework. We will see how the Entities facilitate validations using partial methods. We will also briefly look into the concept of partial classes and partial methods in C#.

Background

There are many a times when we need to perform the business rule validations while inserting or updating the data in a database. While using classic ADO.NET this can be done easily in Business Logic Layer of Data Access Layer.

If we are using Entity framework in our Data Access Layer then how can we ensure that the business rule validations are followed while working with entities. Entity framework provides us a beautiful mechanism for performing validations. This is facilitated by the use of partial functions. Let is look at how we can use the partial functions and perform validations with entity framework.

Using the code

A look into the partial classes and partial methods.

C# provides the flexibility of splitting the class definitions across multiple files using partial methods. This was particularly useful when the IDE generated code was used in unison with the custom code. we can simply split the class definition in multiple places by using the partial keyword. Following code shows how the partial classes can be defined in C#.

C#
// Assume this is the class definition we are not supposed to touch
partial class Person
{
    string m_Name;
    string m_Designation;

    public string Name
    {
        get
        {
            return m_Name;
        }
    }

    public string Designation
    {
        get
        {
            return m_Designation;
        }
        set
        {            
            m_Designation = value;
        }
    }

    public Person(string name, string designation)
    {
        m_Name = name;
        m_Designation = designation;
    }
}

// We can still add functions to this class by having another partial class
// with same name. this will effectively create a single class with all functions.
partial class Person
{
    public override string ToString()
    {
        return string.Format("Name = {0}, Designation = {1}", m_Name, m_Designation);
    }   
}

The concept of partial methods take this approach one step further. It gives me a possibility of creating the declaration of a methods in one partial class and the definition can be provided in another partial class. So let us add a partial method in the first partial Person class in the above code snippet.

C#
partial class Person
{
    string m_Name;
    string m_Designation;

    public string Name
    {
        get
        {
            return m_Name;
        }
    }

    public string Designation
    {
        get
        {
            return m_Designation;
        }
        set
        {
            OnDesignationChanging(value);
            m_Designation = value;
        }
    }

    public Person(string name, string designation)
    {
        m_Name = name;
        m_Designation = designation;
    }

    partial void OnDesignationChanging(string value);
}

What we have done now is that we have created a partial method OnDesignationChanging in the partial class and I am calling this methods whenever someone is setting the designation from outside. Right now the function call will simply be ignored as no definition for the function is present.

So let us not provide the definition of this function in the other partial class so that whenever the function is invoked the definition we provided will execute.

C#
partial class Person
{
    public override string ToString()
    {
        return string.Format("Name = {0}, Designation = {1}", m_Name, m_Designation);
    }

    partial void OnDesignationChanging(string value)
    {
        Console.WriteLine("{0}'s designation has been changed to: {1}", m_Name, value);
    }
}

Now lets see how this function defined in second partial class runs in unison with the existing partial class having the partial method declaration.

C#
static void Main(string[] args)
{
    Person p = new Person("Rahul", "Software Developer");

    // Lets print it
    Console.WriteLine("Person before promotion");
    Console.WriteLine(p.ToString());

    //Lets now try to change the designation
    p.Designation = "Project Manager";

    // Lets print it
    Console.WriteLine("Person after promotion");
    Console.WriteLine(p.ToString());
}
Image 1

So now we can safely say that the partial methods can be used as hooks on the existing classes. the original class can define a partial method and we can hook in our functionality by implementing this partial method.

Recap on Entity framework CRUD Operations

Let us start by creating a small application to perform the basic CRUD operations using entity framework. We will define a small Database with single table for storing the data of Bike and Manufacturer's name.

Image 2

We will then have a class library with entity ADO.NET entities added in this library which will let us access this database. The final application will be a console application that will perform the basic CRUD operations on this table.

Note: Please see the attached sample project for details. Here is only the specific code snippet for CRUD operation only.

C#
// Select
using (MotorBikeShopDbEntities db = new MotorBikeShopDbEntities())
{
    List<bike> bikes = db.Bikes.ToList<bike>();                                
}

// Insert
Bike bike = new Bike();
Console.WriteLine("Enter Bike Name");
bike.BikeName = Console.ReadLine();
Console.WriteLine("Enter Bike Manufacturer");
bike.Manufacturer = Console.ReadLine();
Console.WriteLine("Enter Bike ModelNumber");
bike.Modelumber = Console.ReadLine();

using (MotorBikeShopDbEntities db = new MotorBikeShopDbEntities())
{
    db.Bikes.AddObject(bike);
    db.SaveChanges();
}

// Update
using (MotorBikeShopDbEntities db = new MotorBikeShopDbEntities())
{
    Bike bikeToUpdate = db.Bikes.SingleOrDefault<bike>(p => p.BikeID == bikeID);
    if (bikeToUpdate != null)
    {
        Console.WriteLine("Enter new manufacturer name.");
        string newManf = Console.ReadLine();

        bikeToUpdate.Manufacturer = newManf;
        db.SaveChanges();
    }
}
    
// Delete
using (MotorBikeShopDbEntities db = new MotorBikeShopDbEntities())
{
    Bike bikeToDelete = db.Bikes.SingleOrDefault<bike>(p => p.BikeID == bikeID);
    if (bikeToDelete != null)
    {
        db.DeleteObject(bikeToDelete);
    }
}
</bike></bike></bike></bike>

Lets see this code in action:

Image 3

Important: The sample project contains the complete Data access layer with entity framework and the console application with full code. To run the sample application just create the database and the table as shown above, change the configuration string in App.config of the console application and the application will run.

Note: To read more about the CRUD operations using Entity Framework refer: An Introduction to Entity-Framework for Absolute Beginners 

Validations using Entity framework 

Now if we look at the generated entities, we can see that the entity classes provides partial methods like OnChanging and OnChanged.

Image 4

What we need to do is to simply create a partial class with the same name as the Entity class and inside that class implement this partial method. In this partial method we can write our custom validation logic to validate against the business rules.

Let us say we want to perform a validation that the user should not be able to add a manufacturer name with numbers. To do that we need to implement the the OnManufacturerChanging function. So let us add a partial class with the same name as our Entity i.e. Bike and then implement this function.

C#
public partial class Bike : EntityObject    
{
    partial void OnManufacturerChanging(global::System.String value)
    {
        if (Regex.IsMatch(value, @"^[a-zA-Z]+$", RegexOptions.None) == false)
        {
            throw new Exception("Manufacturer name should only contain alphabets");
        }
    }
}

Now whenever we will try to add or update the data with manufacturer name containing a number the exception will be thrown which we can handle in our application and then notify the user.

Image 5

This way we can put in hooks whenever the entities are changing or changed. This provides a very clean way of handling the validation scenarios while using entity framework.

Note: To run the solution, please create the Database with the above shown table and then change the database path of ConnectionString in the App.config file.

Point of interest

We tried to look into the partial methods and partial functions and how the partial functions can be used as hooks with the classes. We saw how we can use the partial functions provided by Entity framework to perform custom validations.

History

  • 06 October 2012: First version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
GeneralMy vote of 5 Pin
luizfredericojr9-Oct-12 7:19
professionalluizfredericojr9-Oct-12 7:19 
GeneralMy vote of 5 Pin
Member 94902656-Oct-12 11:13
Member 94902656-Oct-12 11:13 
very good!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.