Migrations in separate assembly how to avoid hardcoded connection string?

.net-core asp.net-core database-migration ef-migrations entity-framework-core

Question

I'm writing ASP.NET Core and Entity Framework Core application and I want to store my data access layer in separate assembly, so I followed this tutorial: http://www.michael-whelan.net/ef-core-101-migrations-in-separate-assembly/

But I would also like to avoid hardcoding connection string. I tried to store it in JSON config file or as environment variable and get it using ConfigurationBuilder but when using command line migration tool dotnet ef migrations none of these are available. Is there any way to solve this problem? I'm using 1.0.1 versions of both .NET Core and EF Core.

1
2
12/7/2016 8:00:29 AM

Popular Answer

To solve this issue I create a class library only for migration with a DbContext deriving from my DbContext but with hard connected connection string.

using Microsoft.EntityFrameworkCore;

namespace ChatLe.Repository.Identity.SqlServer
{
    public class ChatLeIdentityDbContext: ChatLe.Models.ChatLeIdentityDbContext
    {
        public ChatLeIdentityDbContext()
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=chatle;Trusted_Connection=True;MultipleActiveResultSets=true");
            base.OnConfiguring(optionsBuilder);
        }
    }
}

Then I launch ef tool command like this :

  • To add a migration run dotnet ef --startup-project {path to my startup project} migrations add login-activity --context ChatLe.Repository.Identity.SqlServer.ChatLeIdentityDbContext
  • To upgrade the database run dotnet ef --startup-project {path to my startup project} database update --context ChatLe.Repository.Identity.SqlServer.ChatLeIdentityDbContext

Read the full sample on my git hub project : https://github.com/aguacongas/chatle/tree/develop/src/ChatLe.Repository.Identity.SqlServer

2
12/7/2016 8:16:53 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow