Saturday, November 20, 2010

Database provisioning in EF code first development

Code first development feature in EF4 CTP creates the default database using SqlClient against localhost\SQLEXPRESS instance with the same name used for the DataContext. EF allows us to change the default behavior of the DB provisioning by creating a new connection and passing the instance to the Database object for connection. You can tweak the default SqlClient convention to connect to a different database of your own convention by implementing the IDbConnectionFactory interface.
namespace System.Data.Entity.Infrastructure
{
    public interface IDbConnectionFactory
    {
        DbConnection CreateConnection(string nameOrConnectionString);
    }
}
The active IDbConnectionFactory can be retrieved or set via the static property, Database.DefaultConnectionFactory.  For e.g, in my class initialize method for the Fixture class I have specified the DefaultConnection to be used as.

Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=MYSERVER\SQLEXPRESS;Initial Catalog=MyDBName;Integrated Security=True;Pooling=False");

Entity framework allows other ways to specify which database should be connected to. You can use the connection strings section in the AppConfig file to specify the default connection and mention the name in the constructor of the DBContext file.
public OrderDbContext() :
            base("AppConfigConnectionStringName") { }

or pass the connection string as constructor parameter for the DBContext as

public OrderDbContext() :
            base(@"Data Source=MYSERVER\SQLEXPRESS;Initial Catalog=MyDBName;Integrated Security=True;Pooling=False") { }

No comments: