Get Entity Framework connection string from alternate location?

How can I retrieve the Entity Framework 4 connection string from a custom config file, not web.config?

Edit: Is it reasonable to delete the default constructor generated code and recreate it in a partial class to use the pulled in connection string?

I would really like to avoid changing all references to the EF context with an overloaded method including the connection string.

@BrokenGlass: This is what we ended up with:

public partial class STARSEntities
{
    private const string _connectionStringFormat = @"metadata=res://*/STARS.EntityModel.STARSModel.csdl|res://*/STARS.EntityModel.STARSModel.ssdl|res://*/STARS.EntityModel.STARSModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source={0};MultipleActiveResultSets=True'";

    /// <summary>
    /// Initializes a new STARSEntities object using the connection string found in the STARS.xml configuration file.
    /// </summary>
    /// <remarks>
    /// If the STARSEntities class is regenerated from the database, the default constructor needs to be removed from the generated file.
    /// </remarks>
    public STARSEntities() : base(GetConnectionString(), "STARSEntities")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }

    private static string GetConnectionString()
    {
        return string.Format(_connectionStringFormat, ApplicationConfiguration.GetConnectionString("STARS"));
    }

}

Answers


There's a constructor overload for DataContext that you can pass a connection string - in that case you can take the setting from anywhere you like.

Edit based on updated question:

I would really like to avoid changing all references to the EF context with an overloaded method including the connection string.

The problem is that the Entities context created by the T4 script generates a const property that is used as connection string

    public const string ConnectionString = "name=FooEntities";

    public FooEntities()
        : base(ConnectionString, ContainerName)
    {
        this.ContextOptions.LazyLoadingEnabled = true;
    }

Since you can't override the default constructor of the partial class, your only other option would be to change the T4 script itself - you should see the following in your .TT script file:

    public <#=code.Escape(container)#>()
        : base(ConnectionString, ContainerName)
    {
<#
        WriteLazyLoadingEnabled(container);
#>
    }

To force your connection string to be used you could modify the constructor call to determine the connection string by calling a static method that you define in a separate file (but for the same partial class FooEntities):

    public <#=code.Escape(container)#>()
        : base(GetCustomConnectionString(), ContainerName)
    {
<#
        WriteLazyLoadingEnabled(container);
#>
    }

Now GetCustomConnectionString() can be defined separately

public partial class FooEntities : ObjectContext
{
   public static string GetCustomConnectionString()
  {
     return "Foobar"; //however you want to determine connection string here
  }
}

You see this is getting complicated and fragile very fast, so I would not advise doing this - but you could.


Don't know if this is what you ask for, but you can use the "configSource" attribute of the connectionStrings element:

<connectionStrings configSource="connection.config">
</connectionStrings>

Something like this perhaps?

// replace the following line with any business logic you need to get to the file
// with your connection string. If it is a config-style file, you can use the 
// Frameworks's helper classes as well
string connectionString= File.ReadAllText("alternative path");
Entities ent = new Entity(connectionString);

Here's a post on Microsoft Connect that explains this.


Are you able to read the connection string from this custom config file? if so, you can use the constructor for your DataContext that takes ConnectionString.

NorthWindDataContext nwdc = new NorthWindDataContext(alternateConnectionString);

You can use EntityConnectionStringBuilder:

var ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Model.MyModel.csdl|res://*/Model.MyModel.ssdl|res://*/Model.MyModel.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = connectionStringFromFancySource;
return new MyModel(ecb.ToString());

Need Your Help

Failed to get dependency from git on git post-update hook

git go githooks

I have a golang project and i want to build it on server as I push it