Monday, April 25, 2011

How do you make one generic select method for your DAL ?


You have an Assembly for Data Transfer Objects containing 10 classes that exactly represent 10 tables in your database. You generate / build a DAL layer that has methods like -

  DTOForTable1[] GetDataFromTable1();
  DTOForTable2[] GetDataFromTable2();

and so on....


How do I make a method that hides the numerous methods to get data from each table from the client code? The method I would want for example in service or business layer could look like-

SomeGenericDTO[] GetDataFromTable(TableTypeEnum tableTypeEnum);
  1. How do I do this ? Is this even possible ?

  2. If yes for (1), is it a good practice ?

  3. If yes for (1) and (2) does this simplifies or complicate design ?

Thanks in advance.

From stackoverflow
  • You could define it like:

    T[] GetDataFromTable1<T>() where T:IDto
       // you can know the table with the type of T

    That said, I would rather either have the different methods or even classes to work with it. I use the repository pattern instead, I suggest to look for info on it.

    Perpetualcoder : I have read about Repository pattern but I dont think i understand it fully. Can you recommend some link ?
    Bill Karwin :
    Bill Karwin : In "Domain-Driven Design" by Eric Evans, chapter 6 contains info about the Repository pattern.
  • Here's how my DAL does it:

    List<entity> customers = SQL.Read(new SearchCriteria(), new Customers());

    To perform joins:

    List<entity> customers = SQL.Read(new SearchCriteria(), new Customers(new Orders(new OrderDetails())));

    The DTO class itself determines which table to access and its properties determine which columns to retrieve.

    I can't answer if it is a best or good practice. It is the practice that has been working for me for a long time. There are no extraneous methods such as "GetById", "GetAll", etc.

    Perpetualcoder : This is very intersting ! Can you provide some link or sample ??
    Otávio Décio : @Perpetualcoder - email me at ocdecio at gmail dot com.
  • It's very common these days to implement your concrete table classes as inheriting an abstract table-access class. The abstract class has generic methods to query a table. Each concrete class can declare which corresponding database table (also perhaps columns and inter-table relationships).

    Design patterns that help include ActiveRecord and Table Data Gateway.


Post a Comment