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

问题描述 投票:0回答:1

我有 ASP.NET Core 1.1 项目,我正在尝试将其转换为 v2.1。

我找到了

IDesignTimeDbContextFactory
实现,但我不明白应该在哪里创建这个工厂的实例以及如何使用它进行迁移正常工作。现在,在创建/删除迁移之前,我必须清理并重建解决方案,因为如果没有,我将收到此消息:

无法创建“MyDbContext”类型的对象。将“IDesignTimeDbContextFactory”的实现添加到项目中,或者参阅 https://go.microsoft.com/fwlink/?linkid=851728 了解设计时支持的其他模式

所有上下文数据都位于单独的项目中。我如何使用

IDesignTimeDbContextFactory
实现或者我做错了什么?

entity-framework-migrations asp.net-core-2.1
1个回答
38
投票

将此类添加到您拥有 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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.