1

I'm currently working on a Azure function project In .NET5.

I have the following project structure:

  • Function.Application
  • Function.Domain
  • Function.Infrastructure

When I try to generate a migration, I get the following error:

Unable to create an object of type 'Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Here Is some code:

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;
    }
}

This approach works well when I develop regular ASP.NET Core applications. I just choose which project the Context are In, and then just type Add-migration dbInit, and It works.

Why does this not work when working with Azure Functions?

Bryan
  • 3,421
  • 8
  • 37
  • 77

1 Answers1

0

Run below command to find the real problem.

Add-Migration Init -Verbose

There are a lot of ways to help you solve the issues.

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

  2. Find real problem and change your code.

For more details , pls check below post.

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

Jason Pan
  • 15,263
  • 1
  • 14
  • 29