jellysaini
jellysaini

Reputation: 158

custom connection string to the entity framework

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.

Upvotes: 1

Views: 3336

Answers (2)

Vishal
Vishal

Reputation: 178

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

Upvotes: 1

Ralf de Kleine
Ralf de Kleine

Reputation: 11734

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.

Upvotes: 1

Related Questions