Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: DbContext and setting the ProviderName

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.

like image 818
NoPyGod Avatar asked Jul 01 '13 08:07

NoPyGod


People also ask

How does DbContext work in Entity Framework?

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.

What is DbContext and DbSet in Entity Framework?

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.

Does DbContext implement IDisposable?

Second, the DbContext class does indeed implement IDisposable out of the box.

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.


1 Answers

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.

like image 186
haim770 Avatar answered Sep 28 '22 02:09

haim770