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 generate the classes from the database structure given as input. For example consider below example
Now I want to display the list of product in my grid but I have to display product name with categoryname for example productname(categoryname) or consider situation where I have ordertable and I have to display one more extra column in grid with display total = quantity * price.
To achieve this make look to the class generated by ORM tools, when you see the class definition you see its decorated with the partial keyword. C#2.0 partial class allow us to create class which expands in two different file and at the time of compile both file get compile in one class. So by making use of same rule I have added one more class file and its partial as below.
Summary
By using partial class we can add the custom logic to the class created by the ORM tool(s).
When you make use of ORM tool like Linq to Sql or Entity-Framework it generate the classes from the database structure given as input. For example consider below example
Now I want to display the list of product in my grid but I have to display product name with categoryname for example productname(categoryname) or consider situation where I have ordertable and I have to display one more extra column in grid with display total = quantity * price.
To achieve this make look to the class generated by ORM tools, when you see the class definition you see its decorated with the partial keyword. C#2.0 partial class allow us to create class which expands in two different file and at the time of compile both file get compile in one class. So by making use of same rule I have added one more class file and its partial as below.
public partial class Product { public string ProductWithCategory { get { return this.ProductName + "(" + this.Category +")"; } } }Now to we can consume property in the presentation or businesslayer like as below.
var productlist = (from p in context.Products select p).ToList(); foreach (Product p in productlist) { Console.WriteLine(p.ProductWithCategory); }So by above way 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).
This detailed step-by-step explanation helps a lot of people. Databases are the key of new systems. I´m going to Argentina the next month and the only thing I know there is going to be in the apartment in buenos aires I booked is that there is a computer. I hope I will still use all of the programs I have installed!
ReplyDeleteAmy