[Updated] Using EF migrations with multi project solutions.

When using ef migrations with an existing project, I found that that entity framework could not get a configuration, so therefore it could not get connection string etc.

The reason for this is that ef migrations look at a few places, for the configuration. I tried a few work arounds, but none of those worked. What seems to work is the following. And it makes sense. Check it out. You can see that we are allowing config to be passed in if we run the application in its typical way.

When we run it in migration mode, we won’t have config info (I think due to my DB project being different to my application project, which contains the startup class) so we check if its configured, then we build. This results in working migrations. I hope it helps!

databaseContext    : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
    public databaseContext()
    {
    }

    public databaseContext(DbContextOptions<databaseContext> options) :
        base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            // Build configuration
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var connectionString = configuration.GetConnectionString("DefaultConnection");
            optionsBuilder.UseSqlServer(connectionString, sqlOption =>
            {
                sqlOption.MigrationsAssembly("Aspnetcoreapp");
                sqlOption.UseNetTopologySuite();
            });
        }


    }

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *