I just wanted to share this Query class and get your thoughts on it. The Query class helps execute queries against a dbconnection. I haven't included the implementation, it's a bit much to post. Here's an example call, you'll get the idea:
OrdersDataTable table =
new Query(connection)
.Table("Orders")
.Fields("OrderID,CustomerID,Description,Amount")
.GreaterThan("OrderID", 1000)
.OrderBy("OrderID")
.Execute<OrdersDataTable>();
Here's the reasons I like the class:
- No need to write the ADO.NET Command code. Calling this class takes up less lines than the ADO.NET equivilent.
- Each member function returns this so multiple calls can be chained together. I'm not sure if there is a name for this pattern. Do you know?
- Handles MySql, OleDb and SqlServer dialects.
- Seems more readable to me than the ADO.NET equivilent.
- Order of calls is irrelevant. All parameters are buffered in internal collections and read when Execute is called.
- My scenario requires me to communicate with multiple database products so I would like to write the query once in a generic manner and just pass in the given connection. It would be alot trouble to leverage db-specific features like stored procs.
I have a DAL that uses this class internally. The UI would make a call into the DAL, passing a few query params and the DataTable is returned. The class has really helped reduce LOC the DAL implementation as well as made it more readable.
Here's a sample DAL call:
OrdersDataTable orders = Orders.GetByOrderId( 1 )
And the impl:
public static OrdersDataTable GetByOrderId( int id )
{
return
new Query(connection)
.Table("Orders")
.Fields("OrderID,CustomerID,Description,Amount")
.Equals("OrderID", id)
.Execute<OrdersDataTable>();
}
Thanks!
Edit: Thanks everyone for the great feedback. Many of you suggested LinqToSql. I did not choose Linq because Microsoft currently only supports Sql Server. I need to query Jet, MySql and Sql Server tables.
Someone asked how AND and OR clauses are constructed. Here an example of each
//and example
public static OrdersDataTable GetByOrderIdAndCustomerId( int orderId, int customerId )
{
return
new Query(connection)
.Table("Orders")
.Fields("OrderID,CustomerID,Description,Amount")
.Equals("OrderID", orderId)
.Equals("CustomerID", customerId)
.Execute<OrdersDataTable>();
}
//or example
public static OrdersDataTable GetByOrderIdOrCustomerId( int orderId, int customerId )
{
return
new Query(connection)
.Table("Orders")
.Fields("OrderID,CustomerID,Description,Amount")
.OrBegin
.Equals("OrderID", orderId)
.Equals("CustomerID", customerId)
.OrEnd
.Execute<OrdersDataTable>();
}