ObjectDataSource Sample:
The source for the project can be downloaded here.
For this example, we'll create a sample business layer, import it into a web project, and bind it to an asp.net webcontrol, without having knowledge of the underlying structure of our data layer. First, we'll add a business layer object to a blank solution. The project "MyBusinessLayer" is a class library containing a BusinessItem, and a BusinessObject. The BusinessObject class' purpose is to directly communicate with the Data Access Layer, and will have knowledge on how to convert say from XML data or SQL data into an enumeration of BusinessItems.
The BusinessItem class is simply a data container object which can in this case hold names and addresses of some collection of people. The important class is really BusinessObject. This provides a method, GetAllBusinessItems, which returns an ICollection, the hook for our DataSource object to connect to.
public static ICollection GetAllBusinessItems()
{
ArrayList al = new ArrayList();//this code should be replaced with real data hooks
//depending on the data access layer's type of results
//ie XML / SQL / raw files, etc.
for (int i = 0; i < 3; i++)
{
al.Add(GetItem(i));
}return al;
}
As shown in the code, it passes values 0,1,2 to GetItem, which returns 3 BusinessItem instances, hardcoded with values. In practice, the GetItem(int itemID) method would pass in information from the raw data object, and get back a business object. Finally, the arraylist is passed out of the layer as an ICollection.
Back on the output side, a new Web Project, ODSWeb is created, and a reference is created to our existing project. (Note that I had one strange bug workaround with this project. I was unable to just add a reference to the MyBusinessObject project to the web project. In order to do this, you'll have to actually reference the DLL, not the project). For this example, we will use the aspx page to declare both the ObjectDataSource and the bound control.
<asp:objectdatasource id="myBOSource" selectmethod="GetAllBusinessItems" typename="MyBusinessLayer.BusinessObject" />
This directly binds the datasource to our ICollection hook, GetAllBusinessItems; asp.net knows how to enumerate through the items, so no actual knowledge of the underlying classes is necessary to iterate through it.
<asp:gridview id="GridView1"
datasourceid="myBOSource" runat="server" />
View the page, and you're good to go. This very simply removes the step of manually binding to the Business layer, and can either be done programmatically or through the aspx page.
Finally some opposing thoughts. Steve Eichert, Frans Bouma, and Thomas Tomiczek all worry about the implications of using objects such as these.
The source for the project can be downloaded here.