.NET Zone is brought to you in partnership with:

I am Microsoft C# MVP July - 2012 My name is Pranay Rana. Currently, I'm working as senior software engineer in a mid-sized company (Ahmedabad). I have 5 years of the experience in web development with Asp.Net, C# and MS SQL server. For me, the definition of programming is: something that you do once and that gets used by multiple users for many years Pranay is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

How to Extend ORM Generated Classes

07.09.2012
| 3159 views |
  • submit to reddit
In this post I am going to show how you can extend the class generated by the .NET ORM tools. To demonstrate I will be using Linq To Sql ORM, but this concept will also work with Entity Framework.

When you make use of ORM tools like Linq to Sql or Entity Framework it generates the classes from the database structure given as input. For example:
Now I want to display the list of products in my grid but I have to display product name with categoryname for example productname(categoryname) or consider a situation where I have 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.  When you see the class definition you see that it's decorated with the partial keyword. C#2.0 partial classes allow us to create a class which expands into two different files and gets compiled in one class at compile time. So by making use of the same rule I have added one more class file and its partial as you can see below.

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 as you can see below.
var productlist = (from p in context.Products select p).ToList();
foreach (Product p in productlist)
{
   Console.WriteLine(p.ProductWithCategory);
}
So using the technique above by adding a property to partial class we can easily achieve the task.

Summary
By using partial classes we can add the custom logic to the class created by the ORM tool(s).
Published at DZone with permission of Pranay Rana, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)