question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Microsoft.EntityFrameworkCore.Tools - Azure Functions with .NET 5 (Isolated) Design-time DbContext Creation with HostBuilder

See original GitHub issue

I have created a new FunctionApp in Visual Studio Version 16.10.0 using the template Azure Functions with .NET 5 (Isolated) and Http trigger.

enter image description here

I have then created the following files:

Blog.cs

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
}

ApplicationDbContext.cs

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(
        DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public DbSet<Blog> Blogs { get; set; }
}

Program.cs

public class Program
{
    public static void Main()
    {
        var host = new HostBuilder()
            .ConfigureFunctionsWorkerDefaults()
            .ConfigureServices(services =>
            {
                var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:DefaultConnection");
                services.AddDbContext<ApplicationDbContext>(options =>
                        options.UseSqlServer(
                        connectionString,
                        sqlServerOptions => sqlServerOptions.CommandTimeout(600)));
            })
            .Build();

        host.Run();
    }
}

Function1.cs

public class Function1
{
    private readonly ApplicationDbContext _applicationDbContext;

    public Function1(ApplicationDbContext applicationDbContext)
    {
        _applicationDbContext = applicationDbContext;
    }

    [Function("Function1")]
    public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
        FunctionContext executionContext)
    {
        var logger = executionContext.GetLogger("Function1");
        logger.LogInformation("C# HTTP trigger function processed a request.");

        var connectionString = _applicationDbContext.Database.GetDbConnection().ConnectionString;

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

        response.WriteString("Welcome to Azure Functions!");

        return response;
    }
}

local.settings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=FunctionApp1.Test;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
  }
}

host.json

{
    "version": "2.0",
    "logging": {
        "applicationInsights": {
            "samplingSettings": {
                "isEnabled": true,
                "excludedTypes": "Request"
            }
        }
    }
}

I have verified that dependency injection works from Program.cs -> new HostBuilder

enter image description here

If I run Add-Migration InitialCreate in Package Manager Console I get the following error:

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

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=vs

https://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=vs

To obtain the DbContext object from the application’s service provider the example code looks like this:

public class Program
{
    public static void Main(string[] args)
        => CreateHostBuilder(args).Build().Run();

    // EF Core uses this method at design time to access the DbContext
    public static IHostBuilder CreateHostBuilder(string[] args)
        => Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(
                webBuilder => webBuilder.UseStartup<Startup>());
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
        => services.AddDbContext<ApplicationDbContext>();

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    }
}

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

The tools first try to obtain the service provider by invoking Program.CreateHostBuilder(), calling Build(), then accessing the Services property.

Is there anyway to make Tools work with HostBuilder instead?

Include provider and version information

EF Core version: 5.0.6 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 5.0 Operating system: Windows 10 IDE: Visual Studio 2019 16.10.0

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
MacMcDellcommented, May 15, 2023

I was able to work around this issue implementing IDesignTimeDBContextFactory as above. https://github.com/dotnet/efcore/issues/30897 This post was helpful.

1reaction
Ogglascommented, Jun 17, 2021

@bricelam

  1. Yes I know but even setting a value like this:

$ConnectionStrings = [PSCustomObject]@{DefaultConnection = 'Server=tcp:mySqlServerStuffxxx'}

Will also cause the error Value cannot be null. (Parameter 'connectionString'). My point was showing that DefaultConnection is nested and the solution shown below won’t work:

https://dev.to/azure/using-entity-framework-with-azure-functions-50aa#adding-an-entity-framework-migration

I also tried the solution above with changing to var connectionString = Environment.GetEnvironmentVariable("ConnectionString"); in CreateHostBuilder and then running:

$env:ConnectionString='Server=(localdb)\mssqllocaldb;Database=FunctionApp1.Test;Trusted_Connection=True;MultipleActiveResultSets=true'
Update-Database

This also caused the exception: Value cannot be null. (Parameter 'connectionString').

Is it a dead end with CreateHostBuilder?

  1. I did not think about that! Worked after fixing this.

  2. Really nice. I first tried with -ConnectionString but got this error:

Update-Database : A parameter cannot be found that matches parameter name ‘ConnectionString’.

After reading documentation I saw that the parameter was actually -Connection. After trying that it worked like a charm with the simple IDesignTimeDbContextFactory below.

https://docs.microsoft.com/en-us/ef/core/cli/powershell#update-database

Update-Database -Connection 'Server=(localdb)\mssqllocaldb;Database=FunctionApp1.Test;Trusted_Connection=True;MultipleActiveResultSets=true'
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer();

        return new ApplicationDbContext(optionsBuilder.Options);
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Azure Functions with .NET 5 (Isolated) Design-time ...
I have created a new FunctionApp in Visual Studio Version 16.10.0 using the template Azure Functions with .NET 5 (Isolated) and Http trigger...
Read more >
Guide for running C# Azure Functions in an isolated worker ...
This article is an introduction to working with .NET Functions isolated worker process, which runs your functions in an isolated worker ...
Read more >
azure functions 7.0 dotnet-isolated read connection string ...
azure functions 7.0 dotnet-isolated read connection string (no startup class) to setup entity framework dbcontext. var host = new HostBuilder() ...
Read more >
Using Entity Framework with Azure Functions | by Jeff Hollan
Let's create a simple Azure Function that can interact with stateful data using Entity Framework Core. I'm going to create a very simple...
Read more >
Issue with DbContext using EntityFrameworkCore Migrations ...
Coding example for the question Issue with DbContext using EntityFrameworkCore Migrations with Azure Functions-entityframework core.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found