Click here to Skip to main content
Click here to Skip to main content

Extend ORM generated class

, 2 Dec 2011
Rate this:
Please Sign up or sign in to vote.
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.

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

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

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

So by 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)

Share

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)

 
Hey, I am Pranay Rana, working as a ITA in 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:


Follow on   Twitter   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 2 Dec 2011
Article Copyright 2011 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid