简体   繁体   English

Microsoft.EntityFrameworkCore:没有为此 DbContext 配置数据库提供程序

[英]Microsoft.EntityFrameworkCore: No database provider has been configured for this DbContext

I am attempting to put my connection string in the local settings.json file in an Azur e Function (v3) for entity framework core.我试图将我的连接字符串放在本地设置中。json 文件中的 Azur e Function (v3) 用于实体框架核心。

I am getting an errors saying.我收到一条错误消息。

ystem.Private.CoreLib: Exception while executing function: Function1. ystem.Private.CoreLib:执行 function 时出现异常:Function1。 Microsoft.EntityFrameworkCore: No database provider has been configured for this DbContext. Microsoft.EntityFrameworkCore:没有为此 DbContext 配置数据库提供程序。 A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider.可以通过覆盖 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。 If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.如果使用 AddDbContext,则还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions object 并将其传递给 DbContext 的基本构造函数。

So I have removed the connection string in OnCofiguration on the context所以我在上下文中删除了 OnCofiguration 中的连接字符串

     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning 
            // optionsBuilder.UseSqlServer("Server=tcp:xxxxx.database.windows.net,1433;Initial Catalog=CatsDB;Persist Security Info=False;User ID=!;Password=!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
            }
        }

I am using Dependency Injection in a startup.cs class:我在 startup.cs class 中使用依赖注入:

[assembly: FunctionsStartup(typeof(Startup))]

namespace Shizzle
{
    class Startup : FunctionsStartup
     {
    
      public override void Configure(IFunctionsHostBuilder builder)
      {
          builder.Services.AddDbContext<CatsDBContext>(
                options => options.UseSqlServer(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString));
      }
     }

And finally I am storing the connection string in local.settings.json最后我将连接字符串存储在 local.settings.json

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  },
  "ConnectionStrings": {
    "SqlConnectionString": "Server=tcp:xxxx.database.windows.net,1433;Initial Catalog=CatsDB;Persist Security Info=False;User ID=!;Password=0!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;"
  }
}

and this is the DBContext:这是 DBContext:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Shizzle.Models
{
    public partial class CatsDBContext : DbContext
    {
        public CatsDBContext()
        {
        }

        public CatsDBContext(DbContextOptions<CatsDBContext> options)
            : base(options)
        {
        }

Any ideas would be amazing... Thanks任何想法都会很棒......谢谢

The startup.cs class should be startup.cs class 应该是

[assembly: FunctionsStartup(typeof(Startup))]

namespace Shizzle
{
    class Startup : FunctionsStartup
     {
    
      public override void Configure(IFunctionsHostBuilder builder)
      {
          builder.Services.AddDbContext<CatsDBContext>(
                options => options.UseSqlServer(Configuration.GetConnectionString("SqlConnectionString")));
      }
 }

This worked for me, but I had to use an ancient EF Core version to be compatible with the current in-process Functions app version (see issuehere ).这对我有用,但我必须使用古老的 EF Core 版本才能与当前的进程内函数应用程序版本兼容(请参阅此处的问题)。

.csproj: .csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.6" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.13" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

And the.cs file:和 .cs 文件:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

[assembly: FunctionsStartup(typeof(FunctionApp5.Startup))]

namespace FunctionApp5
{

    class Startup : FunctionsStartup
    {
        public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
        {
            FunctionsHostBuilderContext context = builder.GetContext();

            var settingsFile = Path.Combine(context.ApplicationRootPath, "local.settingss.json");
            builder.ConfigurationBuilder
                .AddJsonFile(settingsFile, optional: true, reloadOnChange: false);
               // .AddJsonFile(Path.Combine(context.ApplicationRootPath, $"appsettings.{context.EnvironmentName}.json"), optional: true, reloadOnChange: false)
               // .AddEnvironmentVariables();
        }

        public override void Configure(IFunctionsHostBuilder builder)
        {
            
            builder.Services.AddDbContext<CatsDBContext>((sp,options) =>
            {
                var config = sp.GetRequiredService<IConfiguration>();
                var constr = config.GetConnectionString("SqlConnectionString");
                options.UseSqlServer(constr);
             });
        }
    }
    public partial class CatsDBContext : DbContext
    {
        public CatsDBContext()
        {
        }

        public CatsDBContext(DbContextOptions<CatsDBContext> options)
            : base(options)
        {
        }
    }
    public  class Function1
    {
        CatsDBContext db;
        public Function1(CatsDBContext db)
        {
            this.db = db;
        }
        [FunctionName("Function1")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, 
            ILogger log)
        {
            var constr = db.Database.GetDbConnection().ConnectionString;


            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.IO.FileNotFoundException:无法加载文件或程序集 'Microsoft.EntityFrameworkCore,版本 = 2.2.0.0, - System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.EntityFrameworkCore, Version=2.2.0.0, AuthError - 错误:未正确配置 Amplify / AWS cognito,React JS - AuthError - Error: Amplify has not been configured correctly / AWS cognito, React JS [Firebase/Core][I-COR000005] 尚未配置任何应用 - [Firebase/Core][I-COR000005] No app has been configured yet “Microsoft.EntityFrameworkCore.Query.QueryableMethods”的类型初始值设定项引发异常 - The type initializer for 'Microsoft.EntityFrameworkCore.Query.QueryableMethods' threw an exception OpenIDConnect 提供商的 HTTPS 证书与配置的指纹不匹配 - OpenIDConnect provider's HTTPS certificate doesn't match configured thumbprint Azure -- 在本地调试配置了系统标识的 Powershell function - Azure -- debug locally a Powershell function that has System Identity configured 检测用户是否已登录其他提供商 - Detect if user alread has signed in with another provider 需要为帐户 xxx 执行 AWS 调用,但尚未配置凭证 - Need to perform AWS calls for account xxx, but no credentials have been configured Flutter: Firebase 尚未正确初始化 - Flutter: Firebase has not been correctly initialized flutter:LateInitializationError:字段“名称”尚未初始化 - flutter: LateInitializationError: Field 'name' has not been initialized
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM