Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding code-generated DbContext constructor

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?

like image 889
Chris Dixon Avatar asked Feb 26 '13 11:02

Chris Dixon


People also ask

Does DbContext need to be disposed?

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.

Is DbContext thread safe?

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.

Is DbContext part of Entity Framework?

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.

What is DbContext and how is it used?

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.


1 Answers

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().

like image 112
Marc Gravell Avatar answered Oct 13 '22 00:10

Marc Gravell