top of page

As an Amazon Associate we earn from qualifying purchases, more info...

Writer's pictureMark Redman

IDesignTimeDbContextFactory update for Entity Framework 6 migrations (design time tools .net core 6)

One of the things I ran into when updating a .net core 5 project to .net core 6, particularly the DbContextFactory for migrations, where the data models and migrations are located in another class, is the reference to the database connection string from thge appsettings.json file.


Have a look at the changes below that made this work for me.




.Net Core 5 DbContextFactory

This is a typical DbContextFactory for .net Core 5


using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace App.Data
{
    public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
     
            var dbContextOptionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
 
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            dbContextOptionsBuilder.UseSqlServer(connectionString);
            return new ApplicationDbContext(dbContextOptionsBuilder .Options);
        }
    }
}

.Net Core 6 DbContextFactory This is very much the same apart from the way the configuration is setup to get the connection string


using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace App.Data
{
    public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            var configuration = builder.Configuration;
            configuration.SetBasePath(Directory.GetCurrentDirectory());
            configuration.AddJsonFile("appsettings.json");

            var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

            var dbContextOptionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
            dbContextOptionsBuilder.UseSqlServer(connectionString);
            return new ApplicationDbContext(dbContextOptionsBuilder.Options);
        }
    }
}

Hope this helps.





1,907 views0 comments

Recent Posts

See All

ความคิดเห็น


bottom of page