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

25
我有一个ASP.NET Core 1.1项目,我正在尝试将其转换为v2.1。
我找到了IDesignTimeDbContextFactory的实现,但我不明白我应该在哪里创建这个工厂的实例,以及如何将其用于正常的迁移工作。现在,在创建/删除迁移之前,我必须清理和重新构建解决方案,因为如果不这样做,我将收到以下消息:
无法创建类型为'MyDbContext'的对象。向项目添加一个'IDesignTimeDbContextFactory'的实现,或参见https://go.microsoft.com/fwlink/?linkid=851728以获取设计时支持的其他模式。
所有上下文数据都在一个独立的项目中。我应该如何使用IDesignTimeDbContextFactory的实现,或者我做错了什么?
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);
        }
    }

谢谢,看起来问题出在MyDbContextFactory和MyDbContext的不同项目和命名空间上。 - Vitaliy
1
很好!正是我在寻找的。 - snapper
根据文档,这个类也可以添加到启动项目中。 - derekbaker783
1
@derekbaker783 设计时构建器是用于设计时目的。启动注册是用于运行时。 - Ali.Rashidi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接