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

Extended ORM generated class

, 24 Oct 2011
Rate this:
Please Sign up or sign in to vote.
Extended ORM generated class
In this post, I am going to show how you can extend the class generated by the ORM tools. To demonstrate, I am using Linq To SQL ORM.
 
When you make use of 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 product name with categoryname for example productname(categoryname) or consider the situation where I have ordertable and I have to display one more extra column in grid with display total = quantity * price.
 
To achieve this, take a look at the class generated by ORM tools, when you see the class definition you see it's decorated with the partial keyword. C#2.0 partial class allow us to create class which expands in two different files and at the time of compile, both files get compiled in one class. So by making use of the same rule, I added one more class file and it's partial as below:
 
View source
 
public partial class Product
{
   public string ProductWithCategory
   {
      get
      {
         return this.ProductName + "(" + this.Category +")";
      }
   }
}
Now we can consume property in the presentation or businesslayer like below.
 
View source
 
1.var productlist = (from p in context.Products select p).ToList();
2.foreach (Product p in productlist)
3.{
4.   Console.WriteLine(p.ProductWithCategory);
5.}
So by the above method adding property to partial class, we can easily achieve the task.
 
Summary
By using partial class, we can add the custom logic to the class created by the ORM tool(s).
 
Reference from Linq and C#.

License

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

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.140709.1 | Last Updated 24 Oct 2011
Article Copyright 2011 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid