且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 ASP.NET Core 2.1 中使用 IDesignTimeDbContextFactory 实现?

更新时间:2023-02-16 09:52:52

将此类添加到您拥有 DbContext 的文件夹中.

Add this class to folder where you have your DbContext.

public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
    {      

        MyDbContext IDesignTimeDbContextFactory<MyDbContext>.CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var builder = new DbContextOptionsBuilder<MyDbContext>();
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            builder.UseSqlServer(connectionString);

            return new MyDbContext(builder.Options);
        }
    }