When you derive from DbContext and use the parameter-less constructor it will load a connection string from web.config. You also have the option of explicitly specifying the connectionString using one of the other DbContext constructors.
My particular situation dictates that the connection string CANNOT be specified in the web.config, as the location of the server/username and password are determined at runtime. Easy fix right? Just use the above mentioned constructor to specify the connection string? Wrong.
The problem is that when you specify the connection string using said constructor, it still attempts to use the default provider, so if you're using one or more non standard providers, as I am, it will not work.
I'm sure I can change the default provider in the web.config, but I want to use multiple providers so this will not do.
The only possible way around this that I can see is to use ObjectContext instead of DbContext, which seems to allow you to specify the provider along with the database connection string.
Is there any other way to do it? Is my workaround fairly reasonable?
I believe I can also create a DbContext from an ObjectContext instance.
As per Microsoft “A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns.” In simplified way we can say that DbContext is the bridge between Entity Framework and Database.
DbContext generally represents a database connection and a set of tables. DbSet is used to represent a table. Your code sample doesn't fit the expected pattern.
Second, the DbContext class does indeed implement IDisposable out of the box.
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.
Create your DbConnection
manually and pass it to the DbContext
constructor as follows:
var conn = DbProviderFactories.GetFactory("MY_CONN_PROVIDER").CreateConnection(); conn.ConnectionString = "MY_CONN_STR"; new DbContext(conn, true);
Notice the second parameter bool contextOwnsConnection
is true
. Since you don't re-use the connection elsewhere, it lets the context manage the connection and Dispose()
it when needed.
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