by aherrick
21. July 2008 00:54
I have been working with SubSonic for almost a year now and I love it. If you don't know, SubSonic is a data access layer that will automatically generate code to access your data along with a bunch of other really cool tools. Created by Rob Conery, check him out if you have not, version SubSonic 2.1 was just released. I'm going to try and blog about different things I pick up about SubSonic that I hope proves to be useful.
Creating a partial class to extend a a generated SubSonic class is easy! Let's take a look...
When creating SubSonic based projects, we like to create a class library to abstract SubSonic from the web project. You can name this project whatever you like.
In this example I am going to use the Products table from Microsoft's Northwind database. In my SubSonic project class I create a new folder to hold my partial class. I call the folder "DAL"
Create a new class in your DAL folder with the same name as the SubSonic class. For example, SubSonic generates "Product.cs". If you wanted to extend this class, the only trick is to put the keyword "partial" in your new class. See below.
I am going to write a simple method to extend the generated SubSonic Product class. This method "GetProductsToOrder" will return a collection of products where UnitsInStock is less than 20. Of course this is just an arbitrary business rule used as an example. See the code below.
Now to use this method, since I made it static, I do not have to create a new instance of Product. I will set it equal to a ProductCollection and pass it an integer.
Now I have a collection of Products with less than twenty units in stock! Good luck writing your SubSonic partial classes and let me know how it goes!