2

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 Answer 1

1

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

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

2 Comments

It's the same as in the tutorial I followed but there IDbContextFactory<> is used instead of deriving context. It still does not resolve the problem with hardcoding connection string.
I agree but this specific assembly is used only for dev to generate migration, not in your production environment and it's not referenced by your application.

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.