1

How to assign the custom connection string to the entity framework? By default entity framework read the connection string from the web config file or app config file. I want to create a connection string in a string variable and assign the connection to entity framework. So that entity framework creates the connection bridge from that connection string.

We can also say it as entity framework connection string at runtime.

Please help me how we can do this.

2
  • you can have multiple connectionstrings in your config files, and read the one relevant to the context at runtime. Do you plan to construct one on the fly ? Commented Apr 12, 2013 at 5:01
  • Yes I want to construct it on the fly. And provide that connection string to the entity framework context at runtime. Commented Apr 12, 2013 at 5:03

2 Answers 2

1

he easiest way to do this is to create a partial class in your DAL that inherits your Datacontext class, this class has a simple constructor that allows for the connection string to be passed into the class and creates your DataContext entities.

Now to simplify things even more in 99% of my projects and solutions I create a parameterless constructor that reads a static connection string via a custom configuration section created in my data access layer. Therefore i simply call a new Class() and it creates my DataContext for me with the configuration created in the instance. This allows easy use across multiple assemblies, projects (and project types) making deployment and configuration really simple.

Here is an example of a simple class structure that uses a configuration handler, and supports for multiple projects.

First off create you data context as normal. Then create a partial class to extend it something like.

http://forums.asp.net/t/1747809.aspx/1

Sign up to request clarification or add additional context in comments.

Comments

1

Entity Framework Context inherits from DbContext. With some editing of the TextTemplate file you could add a new constructor and use your ConnectionString.

The obvious place to start would be around here (Context.tt line 57 EF5):

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
    public <#=code.Escape(container)#>()
        : base("name=<#=container.Name#>")
    {
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
        this.Configuration.LazyLoadingEnabled = false;
<#
}

Here the tt generates the constructor which calls the Base constructor of DbContext. Here's your hook.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.