Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework DbContext in Azure Web Role

I am migrating an existing Web Application (using Entity Framework 5) to an Azure Web Role.

The database connection string is being moved from the web.config to the ServiceConfiguration.*.cscfg files.

The problem is that in the auto-generated Model.Context.cs file, my entities class is defined like this:

public partial class MyEntities : DbContext
{
    public MyEntities()
        : base("name=MyEntities")
    { }

    // DbSets, etc
}

This will always look for MyEntities in the web.config. How can I override this constructor so that I can pass in the connection string from the ServiceConfiguration.*.cscfg file?

I could derive from this class, like so:

public class MyCloudEntities : MyEntities
{
    public MyCloudEntities()
        : base(CloudConfigurationManager.GetSetting("MyEntities"))
    { }
}

But then I have to change every instantiation of MyEntities in the code base, and it wont prevent developers from using MyEntities in the future.

like image 854
Dave New Avatar asked Jul 16 '13 14:07

Dave New


People also ask

Can we use Entity Framework in Azure function?

Yes, try to remove your default constructor from MyDbContext . Use the below sample and working code to connect the azure function to database using EF . Step 1:- In Startup file use below code. Step 3 :- Create Azure function and use below code.

What is a DbContext in Entity Framework?

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. Entity Framework Core does not support multiple parallel operations being run on the same DbContext 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.


1 Answers

You can change Model.Context.tt file, to use

CloudConfigurationManager.GetSetting("MyEntities")

in place of

"name=MyEntities"

for MyEntities

So each time when context will be re-created, you will always have your changes. In this case you don't need to change anything else.

like image 92
Ivan Sokalskiy Avatar answered Oct 13 '22 12:10

Ivan Sokalskiy