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?
Don't dispose DbContext objects. Although the DbContext implements IDisposable , you shouldn't manually dispose it, nor should you wrap it in a using statement. DbContext manages its own lifetime; when your data access request is completed, DbContext will automatically close the database connection for you.
DbContext is not thread-safe. Do not share contexts between threads. Make sure to await all async calls before continuing to use the context instance.
The DbContext class is an integral part of Entity Framework. An instance of DbContext represents a session with the database which can be used to query and save instances of your entities to a database. DbContext is a combination of the Unit Of Work and Repository patterns.
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With