c# - 添加依赖注入(inject)后,Add-Migration 出现错误

标签 c# .net azure entity-framework-core

将依赖项注入(inject)添加到我的 Azure Function 项目后,我无法再运行“Add-Migration”和“Update Database”。

EntityFrameWorkCore(.Design、.SqlServer、.Tools)-包位于 v6.0.0

我的DbContext:

    public class ContosoDbContext : DbContext
{
    public DbSet<ContosoTable> Contoso { get; set; }
    public ContosoDbContext(DbContextOptions<ContosoDbContext> options) : base(options) { }
}

我的创业:

    public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        var configuration = builder.GetContext().Configuration;
        var connectionString = configuration["ConnectionStringToDb"];

        builder.Services.AddDbContext<ContosoDbContext>(
            options => options.UseSqlServer(connectionString)
        );
    }
}

另请阅读如何使用 IDesignTimeDbContextFactory 在添加依赖注入(inject)后使其正常工作:

    public class ContosoDbContextFactory : IDesignTimeDbContextFactory<ContosoDbContext>
{
    public ContosoDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("local.settings.json")
            .Build();

        var builder = new DbContextOptionsBuilder<ContosoDbContext>();

        var connectionString = configuration["ConnectionStringToDb"];
        builder.UseSqlServer(connectionString);

        return new ContosoDbContext(builder.Options);
    }
}

不知何故,我在运行Add-Migration时收到此错误:

Exception has been thrown by the target of an invocation.

有什么想法吗?

最佳答案

在我的 Azure Functions 启动类中,配置的加载方式与典型 ASP.NET Core 应用程序中的加载方式不同。在为我的案例构建配置时,Azure Functions SDK 会自动处理 local.settings.json 中嵌套的“值”。

因此,当我在 Startup 类中使用 configuration["AzureSettings:Database"] 时,它可以正常工作。

但是,如果您使用迁移等 EF 设计时工具,它们不会意识到 Azure Functions 的这种特殊行为。这就是为什么您应该在 DesignTimeDbContextFactory 中使用嵌套的“值”。

因此,在这种情况下,您需要使用configuration["Values:AzureSettings:Database"]

关于c# - 添加依赖注入(inject)后,Add-Migration 出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76884573/

相关文章:

c# - 如何使用DrawingBrush作为Window.Icon?

c# - 在不破坏不变性的情况下更改属性值

c# - 为什么我的 Rx.NET observable 似乎生成了整个序列两次?

Azure Data Lake 存储 Gen2 权限

c# - XMLSerializer 到 XElement

.net - 在 ASP.Net 中使用模板生成 JavaScript

c# - 在生产环境中运行的 ASP.NET 应用程序崩溃了

c# - 旧的原生应用程序可以在Windows8平板电脑上运行吗?

javascript - 在不使用 Ajax 调用服务器等的情况下实现 Web 应用程序的通知

azure - 使用 key 保管库的更安全方式