Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Extend ORM Generated Class

0.00/5 (No votes)
2 Dec 2011 1  
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, 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 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here