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.