When Static Methods Apply

In my current project we are using Dependency injection and are trying to depend on abstractions instead of implementations as much as possible. Someone recently added a static method call to resolve mappings of properties between a DTO and an Entity. My first reaction to this was that it should not be static. When asked why, I stated that if the mapping was static then wherever it is called I have to know what it is doing in order to unit test code that contains calls to it. When I heard myself say this it made me think, if it does not impact my ability to unit test code that calls it maybe it’s ok? I still think it is better to not directly couple the mapping implementation to callers, but if it does not impede the ability to unit test the callers then really it is more of standards question. So, in light of that if your standard isn’t to inject all dependencies and a dependency does not cause testing difficulty then I suppose it is ok.

That said I think there is value in sticking to standards so that readers of your code and other developers have a reasonable expectation of what they’ll find in a given circumstance. That is debatable, however.

EF Code First Needs Master Database Access

At my current client they are beginning to move towards EF code first for data access. This is a large improvement over their home grown system. I did have one hiccup initially. The connection I am using for my EF DbContext is an already existing connection that does not have credential information on it. Apparently when calling through the DbContext for the first time EF queries the master database to make sure the database you want actually exists. Not sure why they chose to do this, but OK. Problem arises in that my connection does not have access to the master database, only to the one I want to actually connect to, that is already connected to ironically enough.

After googling around some I found that you can tell EF to skip the check to master if you make the below call before your context is ever called:

 Database.SetInitializer<MyContext>(null);

Apparently the above line tells EF to assume you are smart enough to call a database that does exist, and if it does not you can just error, without checking the master db first.

I just put in the constructor of the context so it is not forgotten:

  public class MyContext : DbContext, IMyContext
    {
        public MyContext()
            : base(ApplicationManager.GetConnection, true)

        {
            Database.SetInitializer<MyContext>(null);
        }

If you’ve noticed the static call to get the connection, just ignore it, it’s a whole other story.