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
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:
public partial class Product
public string ProductWithCategory
return this.ProductName + "(" + this.Category +")";
Now we can consume property in the presentation or businesslayer like below.
1.var productlist = (from p in context.Products select p).ToList();
2.foreach (Product p in productlist)
So by the above method adding property to partial class, we can easily achieve the task.
By using partial class, we can add the custom logic to the class created by the ORM tool(s).
Reference from Linq and C#