Smarter ways to use TableAdapter with a base class, an interface, or a partial class

advertisements

C# ADO.Net TableAdapter objects does not implement and interface nor a base class (other than Component).

Anyone used TableAdapter in a Template like (GoF-) pattern?

Update: I would like to solve the problem described here:
Help to improve a migration program
by using template (GoF), adapter (GoF) or other nice patterns.


TableAdapters do not have concrete base class or interface. But the MS guys are smart enough to leave partial. So you can play with the TableAdapter with the partial class. We ran into similar problem where we wanted to write generic code that can address all table-adapters in the data-model. we did it as following.

1.) Defined an interface ITableAdapter

public interface ITableAdapter<TDataTable> : IDisposable
    where TDataTable : DataTable
{
    void AttachTransaction(SqlTransaction _transaction);
    SqlTransaction CreateTransaction();

    int Update(TDataTable _dataTable);

    TDataTable GetData();
    TDataTable GetById(int Id);
}

2.) Later we created partial classes for each table-adapter in the project and implemented this interface for them.

public partial class UsersTableAdapter : ITableAdapter<FileParkDataSet.UsersDataTable>
{
    #region ITableAdapter<UsersDataTable> Members

    public void AttachTransaction(SqlTransaction _transaction)
    {
        if (this.Adapter == null)
            this.InitAdapter();

        this.Adapter.InsertCommand.Transaction = _transaction;
        this.Adapter.UpdateCommand.Transaction = _transaction;
        this.Adapter.DeleteCommand.Transaction = _transaction;

        foreach (var _cmd in this.CommandCollection)
        {
            _cmd.Transaction = _transaction;
        }
    }

    public SqlTransaction CreateTransaction()
    {
        if (this.Connection.State != ConnectionState.Closed)
            this.Connection.Close();
        this.Connection.Open();

        return this.Connection.BeginTransaction();
    }

    #endregion
}

Now you can program against ITableAdapter.