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
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)
So by the above way, by adding a property to a partial class, we can easily achieve the task.
By using a partial class, we can add custom logic to a class created by the ORM tool(s).