Thursday, June 9, 2011

Entity Framework Connection Strings

One of the annoying things in Entity Framework is that you have to pass an Entity Framework connectionstring instead of a normal connectionstring. By default such a connectionstring is created for you if you are using the Entity Framework Designer. However if you don’t use the designer or start changing some stuff, it’s easy to get into trouble.

Most of the time I end up with building the connectionstring from code:

private static string CreateConnectionString()
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.MultipleActiveResultSets = true;
sqlBuilder.DataSource = "dbserver;
sqlBuilder.InitialCatalog = "db";
sqlBuilder.UserID = "dbuser";
sqlBuilder.Password = "dbpassword";

EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = "res://*/";
entityBuilder.Provider = "System.Data.SqlClient";

return entityBuilder.ToString();
}
Metadata

One important thing to notice here is the metadata parameter. This parameter tells the Entity Framework where to find your EDMX at runtime. When your application is compiled, the EDMX is split into three parts: CSDL, MSL, and SSDL. The EDMX can be supplied to the application as embedded resources or files on disk.

I’m specifying the metadata by using a *.  This is the simplest approach to a connection string. It will probably fail if your resources don’t happen to have the same name as your model, or if the assembly doesn’t happen to be loaded.

If you want to know more about this metadata attribute and the values it expects, I recommend reading the following blog post: http://blogs.teamb.com/craigstuntz/2010/08/13/38628/

2 comments:

Anonymous said...

Thanks I was looking for a better way than just a sloppy string concatenation method. This is perfect.

JustinTime said...

Does not seem to work with EF 6.