ADO.NET Entity Model Helpers
I'm starting to get into a project using ADO.NET entity model. This is a pretty cool technology, and I like a lot of the features (especially the logical model approach). There are some things I really dislike about Phase 1, like having to delete the entire model or edit SSDL manually (or with XML tool) - anybody know of some free tools available for this? But overall, I like the approach, and the concept, so I look forward to adding features.
Some features I want to add is automatic logging. Sometimes, you just need to know what's going on with your application to see if the logic is working correctly. I often create a logger class, create an ILogger interface with a LogError and LogMessage methods, and create derived classes to log to event log, console, health monitoring, etc. That is out of scope for this article, but I want to focus on the idea of extensibility. I've been reading articles about how to plugin to the provider architecture and other approaches, but I don't personally want to affect the architecture. Rather, I'd rather take the wrapping approach. This is separated and isolated from any provider architecture changes over the years. While that's not a major concern anyway (at least for me), a separate class seems like a good approach.
So I use a class that does something like this:
public class ObjectContextHelpers
{
public static void SaveNewObject(CustomObjectContext context, string entitySetName, object entity)
{
//get a reference to the logger - pass in as ref or via singleton, or some other approach
logger.LogMessage("Attempting to save object for entity set " + entitySetName);
//Can log other details, number of objects commiting, details about object state entries, and other information
try
{
context.AddObject(entitySetName, entity);
}
catch(Exception ex) { logger.LogMessage("Saving object failed: " + ex.ToString()); }
logger.LogMessage("Saved object for entity set " + entitySetName);
}
public static CustomObjectContext Create()
{
return new CustomObjectContext(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
}
}
Here we have a Create method that uses one common connection string, which is a connection string pre-configured (assuming that you aren't building a custom library that may require configurability).