Monday, February 23, 2009

Seperating the ObjectDataSource Service and business objects

In hindsight this seems like a rather trivial example. Still, up until now I've always been configuring ObjectDataSource against a single class. This class provided the CRUD methods and the properties for whatever the data source was connected to.

An alternative approach is to separate the CRUD methods from the business object into a service object. E.g. :

Business object:

using System;

public class Car
{
    private string _vin;

    public string Vin
    {
        get { return this._vin; }
    }

    public Car(string vin)
    {
        this._vin = vin;
    }
}

Service:

using System;
using System.Collections.Generic;

public class CarService
{
 public CarService()
 {
 }

    public List<Car> Select()
    {
        List<Car> cars = new List<Car>();
        cars.Add(new Car("vin1"));
        cars.Add(new Car("vin2"));
        return cars;
    }
}

Default.aspx

    <form id="form1" runat="server">
    <div>
    
    <asp:GridView ID="GridView1" runat="server" DataSourceID="Objectdatasource1">
    </asp:GridView>
    <asp:objectdatasource ID="Objectdatasource1" runat="server" SelectMethod="Select" TypeName="CarService"></asp:objectdatasource>
    
    </div>
    </form>