问题描述
我在 Visual Studio Version 16.10.0
中使用模板 Azure Functions
和 .NET 5(隔离)
和Http触发器
.
然后我创建了以下文件:
博客.cs
公开课博客{公共 int Id { 获取;放;}公共字符串名称 { 获取;放;}}
ApplicationDbContext.cs
公共类 ApplicationDbContext : DbContext{公共应用程序数据库上下文(DbContextOptions选项):基础(选项){}公共数据库集博客 { 得到;放;}}
程序.cs
公共类程序{public static void Main(){var host = new HostBuilder().ConfigureFunctionsWorkerDefaults().ConfigureServices(services =>{var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings:DefaultConnection");services.AddDbContext(options =>options.UseSqlServer(连接字符串,sqlServerOptions =>sqlServerOptions.CommandTimeout(600)));}).建造();主机.运行();}}
Function1.cs
公共类Function1{私有只读 ApplicationDbContext _applicationDbContext;公共功能1(ApplicationDbContext applicationDbContext){_applicationDbContext = applicationDbContext;}[功能(功能1")]public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, get", post")] HttpRequestData req,FunctionContext executionContext){var logger = executionContext.GetLogger("Function1");logger.LogInformation(C# HTTP 触发器函数处理了一个请求.");var connectionString = _applicationDbContext.Database.GetDbConnection().ConnectionString;var response = req.CreateResponse(HttpStatusCode.OK);response.Headers.Add("Content-Type", "text/plain; charset=utf-8");response.WriteString(欢迎使用 Azure 函数!");返回响应;}}
local.settings.json:
{连接字符串":{DefaultConnection":Server=(localdb)\mssqllocaldb;Database=FunctionApp1.Test;Trusted_Connection=True;MultipleActiveResultSets=true"},IsEncrypted":假,值":{AzureWebJobsStorage":UseDevelopmentStorage=true",FUNCTIONS_WORKER_RUNTIME":dotnet 隔离"}}
host.json
{版本":2.0",记录":{应用洞察":{采样设置":{isEnabled":真,excludedTypes":请求"}}}}
我已经通过 Program.cs
验证了依赖注入是有效的 ->新的HostBuilder
如果我在包管理器控制台中运行 Add-Migration InitialCreate
,我会收到以下错误:
无法创建类型为ApplicationDbContext"的对象.为了设计时支持的不同模式,请参阅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
要从应用程序的服务提供者处获取 DbContext 对象,示例代码如下所示:
公共类程序{public static void Main(string[] args)=>CreateHostBuilder(args).Build().Run();//EF Core 在设计时使用此方法访问 DbContext公共静态 IHostBuilder CreateHostBuilder(string[] args)=>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>webBuilder.UseStartup());}公开课启动{public void ConfigureServices(IServiceCollection 服务)=>services.AddDbContext();公共无效配置(IApplicationBuilder 应用程序,IWebHostEnvironment 环境){}}公共类 ApplicationDbContext : DbContext{公共 ApplicationDbContext(DbContextOptions options):基础(选项){}}
工具首先尝试通过调用获取服务提供者Program.CreateHostBuilder(),调用Build(),然后访问服务属性.
有没有办法让工具与 HostBuilder 一起工作?
几天来我遇到了类似的问题.我刚刚看了你的解决方案,它对我帮助很大.但是我没有创建一个 StartUp 类来添加数据库上下文
public static IHostBuilder CreateHostBuilder(string[] args)=>新的主机构建器().ConfigureFunctionsWorkerDefaults().ConfigureServices(service => ConfigureServices(service));
在 ConfigureServices
里面我只有:
services.AddDbContext();
它有效.
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
.
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
If I run Add-Migration InitialCreate
in Package Manager Console I get the following error:
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)
{
}
}
Is there anyway to make Tools work with HostBuilder instead?
I had similar issue for few days now. I just watched your solution and it helped me a lot. But I didn't create a StartUp class to add database context
public static IHostBuilder CreateHostBuilder(string[] args)
=> new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(service => ConfigureServices(service));
Inside ConfigureServices
i just have :
services.AddDbContext<ApplicationDbContext>();
and it works.
这篇关于Microsoft.EntityFrameworkCore.Tools - Azure Functions with .NET 5 (Isolated) Design-time DbContext Creation with HostBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!