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"));
}
}
There’s a constructor overload for
DataContextthat you can pass a connection string – in that case you can take the setting from anywhere you like.Edit based on updated question:
The problem is that the Entities context created by the T4 script generates a const property that is used as connection string
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:
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):Now
GetCustomConnectionString()can be defined separatelyYou see this is getting complicated and fragile very fast, so I would not advise doing this – but you could.