gpt4 book ai didi

entity-framework-migrations - 如何在ASP.NET Core 2.1中使用IDesignTimeDbContextFactory实现?

转载 作者:行者123 更新时间:2023-12-01 23:27:56 35 4
gpt4 key购买 nike

我有ASP.NET Core 1.1项目,我正在尝试将其转换为v2.1。我已经找到了IDesignTimeDbContextFactory实现,但是我不知道该在哪里创建该工厂的实例以及如何将其用于正常迁移。现在,在创建/删除迁移之前,我必须清理并重建解决方案,因为如果没有,我将得到以下消息:Unable to create an object of type 'MyDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<MyDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time。所有上下文数据都在单独的项目中。如何使用IDesignTimeDbContextFactory实现或我做错了什么?

最佳答案

将此类添加到具有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);
}
}

关于entity-framework-migrations - 如何在ASP.NET Core 2.1中使用IDesignTimeDbContextFactory实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50820275/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com