Click here to Skip to main content
15,892,199 members
Articles / Programming Languages / C#

Extend ORM Generated Class

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
2 Dec 2011CPOL1 min read 10.6K   2  
By using a partial class, we can add custom logic to a class created by the ORM tool(s).

In this post, I am going to show how you to extend a class generated by ORM tools. To demonstrate this, I am using a LINQ to SQL ORM.

When you make use of an ORM tool like LINQ to SQL or Entity-Framework, it generates the classes from the database structure given as input. For example, consider the below example:

Now I want to display the list of products in my grid but I have to display the product name with categoryname, for example, productname(categoryname), or consider a situation where I have an ordertable and I have to display one more extra column in the grid with display total = quantity * price.

To achieve this, look at the class generated by the ORM tools. In the class definition, you will see it is decorated with the partial keyword. A C# 2.0 partial class allows us to create a class which expands in two different files and at compile time, both files get compiled in one class. So by making use of the same rule, I have added one more class file and it is partial, as below:

C#
public partial class Product
{
   public string ProductWithCategory
   {
      get
      {
         return this.ProductName + "(" + this.Category +")";
      }
   }
}

Now, we can consume the property in the presentation or business layer, like below:

C#
var productlist = (from p in context.Products select p).ToList();
foreach (Product p in productlist)
{
   Console.WriteLine(p.ProductWithCategory);
}

So in the above way, by adding a property to a partial class, we can easily achieve the task.

Summary

By using a partial class, we can add custom logic to a class created by the ORM tool(s).

License

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


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
-- There are no messages in this forum --