8

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.

Dave New
  • 38,496
  • 59
  • 215
  • 394
  • Why do you want to store the connectionstring in the azure config file? Do you ever need to change the connectionstring at runtime? – Fore Jul 16 '13 at 20:07
  • 2
    No, but the connection string is different per environment. – Dave New Jul 17 '13 at 06:41

1 Answers1

7

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.

Ivan Sokalskiy
  • 812
  • 7
  • 14
  • Where would I change this? I cannot change the context file because it is auto-generated. Thanks for the answer. – Dave New Jul 16 '13 at 15:11
  • 1
    Right, you cannot change context file (Model.Context.cs) because it will be re-created, but that file is generated from the template file (Model.Context.tt). You need to open that Model.Context.tt file as plain text file (VS works just perfect for that) and find place with `base("name=<#=container.Name#>")`, after that just change it to `base(CloudConfigurationManager.GetSetting("MyEntities"))`, save file and click Right Mouse Button on it in Solution Explorer, find "Run Custom Tool" menu item and click it. Model.Context.cs will be re-created with your new changes. – Ivan Sokalskiy Jul 16 '13 at 15:23
  • Since you have changed template, your changes will be not lost. – Ivan Sokalskiy Jul 16 '13 at 15:28