【问题标题】:Unable to create an object of type 'Context'无法创建“上下文”类型的对象
【发布时间】:2021-08-15 11:29:18
【问题描述】:

我目前正在 .NET5 中开发一个 Azure 函数项目。

我的项目结构如下:

  • Function.Application
  • 函数.域
  • Function.Infrastructure

当我尝试生成迁移时,我收到以下错误:

无法创建“上下文”类型的对象。对于不同的 设计时支持的模式,请参阅 https://go.microsoft.com/fwlink/?linkid=851728

这是一些代码:

Function.Application.Program.cs:

public static void Main()
{
    var host = new HostBuilder()
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureServices(services =>
        {
            var localConnectionString = @"Server=(localdb)\mssqllocaldb;Database=information-services-testdb;Integrated Security=True;";
            services.AddDomain(localConnectionString);
        })
        .Build();

    host.Run();
}

Function.Domain.Injections:

public static class Injections
{
    public static IServiceCollection AddDomain(this IServiceCollection services, string connectionString)
    {
        services.AddPersistence(connectionString);

        return services;
    }
}

Function.Infrastructure.Injections:

public static class Injections
{
    public static IServiceCollection AddPersistence(this IServiceCollection services, string connectionString)
    {
        services.AddDbContext<IContext, Context>(
            options => options.UseSqlServer(connectionString),
            ServiceLifetime.Transient,
            ServiceLifetime.Transient);

        return services;
    }
}

当我开发常规 ASP.NET Core 应用程序时,这种方法效果很好。我只需要选择 Context 所在的项目,然后输入Add-migration dbInit,就可以了。

为什么在使用 Azure Functions 时这不起作用?

【问题讨论】:

    标签: c# entity-framework-core azure-functions .net-5


    【解决方案1】:

    运行下面的命令来找出真正的问题。

    Add-Migration Init -Verbose
    

    有很多方法可以帮助您解决问题。

    1. Can add a class that implements IDesignTimeDbContextFactory inside of your Web project.

    2. Find real problem and change your code.

    更多详情,请查看以下帖子。

    Unable to create migrations after upgrading to ASP.NET Core 2.0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-09
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      相关资源
      最近更新 更多