Felipe Lopez
Felipe Lopez

Reputation: 71

Entity Framework - Database First without config

I'm developing a class library that deals with an exiting db using EF. I want to avoid the consumer of the class library (and .exe or a web site) to have in the *.config file the Entity connection string. I want the connection string set a run-time.

How do I set the connection string with Database First approach? There is no constructor overload that takes a connection string and when I created one (in a separate partial class) I got an "UnintentionalCodeFirstException".

I have reviewed already the following links:

Upvotes: 3

Views: 3802

Answers (1)

Matt Whetton
Matt Whetton

Reputation: 6786

There is a constructor on DbContext that takes a DbConnection, and you need to use an EntityConnection object for it:

SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();

// Set the properties for the data source.
sqlBuilder.DataSource = "server name";
sqlBuilder.InitialCatalog = "database name";
sqlBuilder.IntegratedSecurity = true;

// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();

var entityBuilder = new EntityConnectionStringBuilder();

// Initialize the EntityConnectionStringBuilder.
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";

// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;

// Set the Metadata location.
entityBuilder.Metadata = @"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";

using(var context = new YourDbContext(entityBuilder.ToString())){
    //do stuff here
}

The important thing to note is the metadata part - "Model1" obviously needs to be replaced for your model name.

Ref: http://msdn.microsoft.com/en-us/library/bb738533.aspx

EDIT 20/02/2013 22:25

So as an addition you'll need to extend the created DbContext class with a partial class that adds a constructor to support the above code, like this:

public partial class YourDbContext
{
    public YourDbContext(string connection) : base(connection) {}
}

This class needs to be in the same namespace as the DbContext that is generated by the entity framework wizard.

Upvotes: 6

Related Questions