Over a million developers have joined DZone.

How to Extend ORM Generated Classes

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
         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)
So using the technique above by adding a property to partial class we can easily achieve the task.

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 , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}