Search code examples
entity-frameworkentity-framework-6entity-framework-core

How can I load the connection string from App.config or WebConfig.config in Entity Framework Core


In the old versions I can give the connection string directly in the DbContext constructor.

Example in EF v6: My connection string in the App.config is given below:

  <connectionStrings>
    <add name="DatabaseConnecionString"
    connectionString="Data Source=.;Initial Catalog=db;Integrated Security=true"
    providerName="System.Data.SqlClient"/>
  </connectionStrings> 

var myDbContext = MyDbContext("name=DatabaseConnecionString");

When I do the same thing with EF 7 / Core I get an error?


Solution

  • In Entity Framework 7/Core, you cannot pass the connection string name to the DbContext base constructor like in the past but there is another solution for the problem.

    Solution I:

    var optionsBuilder = new Microsoft.EntityFrameworkCore.DbContextOptionsBuilder();
    var connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnecionString"].ConnectionString;
    optionsBuilder.UseSqlServer(connectionString);
     using (var dbContext = new DatabaseContext(optionsBuilder.Options))
     {
        dbContext.Users.Add(new User() { Name = "Bassam" });
        dbContext.SaveChanges();
     }
    

    Solution II:

    If you want to use the provided connection string for the database migrations, then you have to put the loading in the DbContext.

    public class DatabaseContext : DbContext
    {
        public DbSet<User> Users { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
          var connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnecionString"].ConnectionString;
          optionsBuilder.UseSqlServer(connectionString);
        }
    
        public DatabaseContext()
        {
        }
    
        public DatabaseContext(DbContextOptions s)
        : base(s)
        {
        }
    }
    

    If the App.config is not in your Assembly(dll/exe) then you have to give the the startup project with the data migration command Add-Migration/Update-Migration.