I'm sure I've done this before at some stage, but I can't figure out how to now! My scenario:
// This is generated from EDMX
public partial class HOLDbEntities : DbContext
{
public HOLDbEntities()
: base("name=HOLDbEntities")
{
}
}
Now, I want this connection string to be easily changeable (I want to Implement from the HOLDbEntities), so I need to override this constructor.
I've tried:
public partial class HOLDbEntities
{
private const string _contextName = "HOLDbEntities";
public static string ContextName { get { return _contextName; } }
public HOLDbEntities()
: base(ContextName)
{
}
}
But this throw an error:
HOLDbEntities already defines a member called "HOLDbEntities" with the same parameter types.
I can understand why this errors, but how would I stop the constructor being auto-generated in the first place in order to do what I'm trying to achieve?
The best I can suggest is a factory method:
private HOLDbEntities(string contextName) : base(contextName) { }
public static HOLDbEntities Create() {
return new HOLDbEntities(ContextName);
}
and use HOLDbEntities.Create()
rather than new HOLDbEntities()
.
I up-voted the previous accepted answer because it is a fairly elegant way of doing it. However another approach would be to modify the T4 template that generates the dbContext Class.
When using EF DB first you have a .edmx file and under that you have an [Entity].Context.tt file. Go into that file and remove (or modify) the following code:
public <#=code.Escape(container)#>()
: base("name=<#=container.Name#>")
{
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
this.Configuration.LazyLoadingEnabled = false;
<#
}
foreach (var entitySet in container.BaseEntitySets.OfType<EntitySet>())
{
// Note: the DbSet members are defined below such that the getter and
// setter always have the same accessibility as the DbSet definition
if (Accessibility.ForReadOnlyProperty(entitySet) != "public")
{
#>
<#=codeStringGenerator.DbSetInitializer(entitySet)#>
<#
}
}
#>
now your context class will generate without a constructor, so you should be able to go and create one in an extended class.