NetTiers provides a wonderful way of querying a SQL database with strong .NET types and a query simplified language.
For this example, I’m building our queued email sender. I have stored a bunch of emails in the database and it’s time to send them.
In SQL, this is the query I’m trying to achieve:
SELECT
EmailQueue.*
FROM
EmailQueue
WHERE
SentDateTime IS NULL AND
ErrorMessage IS NULL
With NetTiers, I’m going to use the strongly typed ParameterBuilder class, in this case, the generated EmailQueueQuery.
EmailQueueQuery query = new EmailQueueQuery();
query.AppendIsNotNull(EmailQueueColumn.SentDateTime);
query.AppendIsNotNull(EmailQueueColumn.ErrorMessage);
TList<EmailQueue> messages = DataRepository.EmailQueueProvider.Find(query);
foreach (EmailQueue message in messages)
{ // now I have a strong collection of EmailQueue object, send email messages }
There are hundreds of ways to solve this problem. I could use a SQL string or stored procedure and fill a DataReader. I could use a custom stored procedure, regenerate and obtain the same collection of objects. I prefer the method above and here’s why:
1.) Everything is strongly typed. When the model (database schema) changes, my code breaks quickly. When TJ changes the ErrorMessage to ErrorMessageType, regenerates and recompiles, there is going to be a big error message saying WCF.Entities.EmailQueue does not contain a definition for ‘ErrorMessage’. To me, breaking the code quickly (and repairing it quickly) is good. The alternative with the SQL text or stored procedure is to retest every reference to the query. (One of my favorite generated objects from NetTiers is the <T>Column enum, which contains the column names from the target table. No need to flip back to SQL Server to see what you called that field — IntelliSense will provide in Visual Studio!)
2.) I’m sure many DBAs would have my hide for this, but I prefer to keep everything in .NET and Visual Studio. Each time I have to leave the IDE, my attention is distracted. The parameterized query keeps my head down in the space of the problem. If we find during testing, the query is too slow and we need to refactor and replace, we can do that. For now, this is a simple solution which enables fast (as in keystokes, not always performance) database access. For me, it’s better to start simple and make complex as the situation dictates. I’ve found that parameterized queries fit around 90% of my data access needs.