gpt4 book ai didi

c# - Microsoft.EntityFrameworkCore.Tools - Azure Functions 与 .NET 5(独立)使用 HostBuilder 创 build 计时 DbContext

转载 作者:行者123 更新时间:2023-12-03 03:48:49 26 4
gpt4 key购买 nike

我在 Visual Studio 版本 16.10.0 中使用模板 Azure Functions.NET 5 (隔离)Http 触发器

enter image description here

然后我创建了以下文件:

博客.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; }
}

程序.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"
}
}

主机.json

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

我已经验证依赖注入(inject)可以从 Program.cs -> new HostBuilder

enter image description here

如果我在程序包管理器控制台中运行 Add-Migration InitialCreate,我会收到以下错误:

Unable to create an object of type 'ApplicationDbContext'. For thedifferent patterns supported at design time, seehttps://go.microsoft.com/fwlink/?linkid=851728

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

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

要从应用程序的服务提供商获取 DbContext 对象,示例代码如下所示:

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 invokingProgram.CreateHostBuilder(), calling Build(), then accessing theServices property.

有没有办法让 Tools 与 HostBuilder 一起使用?

最佳答案

关于c# - Microsoft.EntityFrameworkCore.Tools - Azure Functions 与 .NET 5(独立)使用 HostBuilder 创 build 计时 DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67834480/

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