Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 set connection string in code

Tags:

I have a dll that uses the Entity Framework 6 to do some database operations. I'm using a database first approach. The model and everything concerning the Entity Framework, like the connection string in the App.config, were created via the wizzard in Visual Studio.

So I compiled the dll and put it together with the corresponding .config in the folder where the application using the dll expects it.

Everything works fine until I get to the point where an actual database call is made. There I get the error:

Cannot find connection string for MyDatabaseEntity

The automatically generated connectionstring is, as I said, in the config file of the dll. I cannot change the App.config of the application. But the application hands over an object that has all the information I need to build the connection string myself. So I'm looking for a way to set the connection string in the code without relying on a config file. All the tutorials I find for a database first approach use this method though. I found a post here that says to simply give the connection string as a parameter when creating the Object like

MyDatabaseEntities = new MyDatabaseEntities(dbConnect);

but ´MyDatabaseEntities´ doesn't have a constructor that takes any parameters

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

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<MyTable> MyTable { get; set; }
}
like image 257
FNR Avatar asked Dec 18 '15 07:12

FNR


People also ask

How do I create a connection string in .NET core?

ASP.NET Core For instance, you can use the Secret Manager tool to store your database password and then, in scaffolding, use a connection string that simply consists of Name=<database-alias> . Or the following example shows the connection string stored in appsettings. json .

How can create connection string in Appsettings JSON?

Method 1: Using the standard locationTo define the connection strings in appsettings. json it is important to specify it in the right section of the JSON structure. Now we can read it in our code by calling the GetConnectionString method in the Microsoft. Extensions.

What is connection string in Entity Framework?

A connection string contains initialization information that is passed as a parameter from a data provider to a data source. The syntax depends on the data provider, and the connection string is parsed during the attempt to open a connection.


2 Answers

How about:

public partial class MyDatabaseEntities : DbContext
{
public MyDatabaseEntities(string connectionString)
    : base(connectionString)
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    throw new UnintentionalCodeFirstException();
}

public virtual DbSet<MyTable> MyTable { get; set; }

}

Then initialize your database like you did before:

string myConnectionString = "...";
MyDatabaseEntities = new MyDatabaseEntities(myConnectionString);
like image 128
Alexander Derck Avatar answered Sep 19 '22 06:09

Alexander Derck


I had the similar issue. My Edmx and App.Config was in a different project. My startup project was different, had 3 different connection strings, we need to choose one on the fly depending on the environment. So couldn't use a fixed connection string. I created a partial class overload of the Context.cs using the same namespace. Following was my default Context.cs;

namespace CW.Repository.DBModel
{

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

      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
        throw new UnintentionalCodeFirstException();
      }
  ...
  ...
  }
}

My partial class overload;

namespace CW.Repository.DBModel
{
    public partial class CWEntities : DbContext
    {
        public CWEntities(string ConnectionString)
            : base(ConnectionString)
        {
        }        
    }
}

Lastly, as my connection strings were not for EF, I converted them to a EF connection string.

public static string GetEntityConnectionString(string connectionString)
    {
        var entityBuilder = new EntityConnectionStringBuilder();

        // WARNING
        // Check app config and set the appropriate DBModel
        entityBuilder.Provider = "System.Data.SqlClient";
        entityBuilder.ProviderConnectionString = connectionString + ";MultipleActiveResultSets=True;App=EntityFramework;";
        entityBuilder.Metadata = @"res://*/DBModel.CWDB.csdl|res://*/DBModel.CWDB.ssdl|res://*/DBModel.CWDB.msl";

        return entityBuilder.ToString();
    }

Lastly, the calling

var Entity = new CWEntities(CWUtilities.GetEntityConnectionString(ConnectionString));
like image 29
Mahib Avatar answered Sep 20 '22 06:09

Mahib