繁体   English   中英

尝试从数据层连接到来自 appsettings.json 的值时,无法创建类型为“PrattleContext”的 object

[英]Unable to create an object of type 'PrattleContext' when trying to connect to value from appsettings.json from data layer

我的应用程序是这样分层的

API -appsettings.json

DAL -configs -appsettings -contexts -mydbcontext

我只是想通过项目将我在应用程序设置中的连接传递给我的 dbcontext 并运行迁移。

当我点击 dotnet ef 迁移时,添加初始

我得到错误

    PM> dotnet ef migrations add changing
    Build started...
    Build succeeded.
    Unable to create an object of type 'PrattleContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
    PM> 

我的 program.cs 文件(在 api 项目中)

using Microsoft.EntityFrameworkCore;
using prattle.Data.Configs;
using prattle.Data.Contexts;

var builder = WebApplication.CreateBuilder(args);


// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//db
builder.Services.AddDbContext <PrattleContext> (option =>
    option.UseNpgsql(builder.Configuration.GetConnectionString("prattleDatabase")));

builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("ConnectionStrings").GetSection("prattleDatabase"));


builder.Services.AddOptions();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

appsettings.json(在 api 项目中)

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "prattleDatabase": "Host=localhost; Database=prattle; Username=develop; Password=develop123;"
  }
}

configs/appsettings(在数据层)

namespace prattle.Data.Configs
{
    public class AppSettings
    {
        public string prattleDBConnectionString { get; set; }
    }
}

contexts/pratlecontext(在数据层)

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using prattle.Data.Configs;
using prattle.Model.Models;

namespace prattle.Data.Contexts
{
    public class PrattleContext : DbContext 
    {
        private IOptions<AppSettings> _appsettings;

        public PrattleContext()
        {

        }


        public PrattleContext(IOptions<AppSettings> appsettings)
        {
            _appsettings = appsettings;
        }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            var dbConnectionInfo = _appsettings.Value.prattleDBConnectionString;

            optionsBuilder.UseNpgsql(dbConnectionInfo);

        }

        public DbSet<User> Users { get; set; }

        public DbSet<Message> Messages { get; set; }
    }
}

我猜问题出在我的 program.cs 文件中,但我不知道为什么?

首先builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("ConnectionStrings").GetSection("prattleDatabase")); 不会像您期望的那样工作, prattleDBConnectionString将是null 要使其工作,您需要匹配 json 属性的名称和代表设置的 class 的属性:

public class AppSettings
{
    public string prattleDatabase { get; set; }
}

然后要正确绑定它,您只需要使用ConnectionStrings部分:

builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("ConnectionStrings"));

另请注意,通过您使用的选项进行设置不是管理 EF Core 上下文的惯用方式,通常您只需要一个接受DbContextOptions的 ctor

public class PrattleContext : DbContext
{
    public PrattleContext(DbContextOptions<PrattleContext> options)
        : base(options)
    {
    }
    // ... db sets
}

所以AddDbContext调用适用于那里指定的参数。

您可能缺少的最后一件事是传递给dotnet ef...的参数。 对于初学者,因为您似乎正在使用 Visual Studio package 管理器控制台,您可以切换到它支持的命令(Powershell),例如Add-Migration 他们将使用您的 VS 中的“默认值”-“默认项目”(将其设置为带有上下文的项目):

在此处输入图像描述

以及在解决方案资源管理器中选择的Startup项目(选择API之一)。

如果您仍想使用dotnet ef 工具,您可能需要指定下一个选项:

选项 短的 描述
--project <PROJECT> -p 目标项目的项目文件夹的相对路径。 默认值为当前文件夹。
--startup-project <PROJECT> -s 启动项目的项目文件夹的相对路径。 默认值为当前文件夹。

-p设置为包含上下文的项目,将-s设置为带有连接字符串的 API 项目。

如何访问列表<object>来自 appsettings.Json?<div id="text_translate"><p> 在我的 appsettings.json 我有一个这样的字段</p><pre> "MyFields": [ { "name":"one", "type":"type1" "parameters":[{"key":"url","value":"myurl.com"}, {"key":"data","value":"mydata"}] }, { "name":"two", "type":"type2"... .. and so on } ]</pre><p> 我制作了一个具有以下属性的 class Myfield:</p><pre> public class MyField { [JsonProperty] public string? name { get; set; } [JsonProperty] public string? type { get; set; } [JsonProperty] public IDictionary<string,string>? parameters { get; set; } }</pre><p> 我正在尝试使用配置在另一个 class 中访问它,如下所示:</p><pre> //config is the configuration var myFields = config.GetSection("MyFields").Get<List<MyField>>();</pre><p> 问题是 myFields 结果是空的。 但是当我通过消除“参数”字段来做同样的事情时,它就像一个魅力。</p><p> 我知道这与匹配不当有关,但能得到一些帮助会很棒。</p></div></object>

[英]How can I access a List<object> from appsettings.Json?

暂无
暂无

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

相关问题 无法从appsettings.json获取价值 从appSettings.json获取价值? 从appsettings.json检索数据 如何访问列表<object>来自 appsettings.Json?<div id="text_translate"><p> 在我的 appsettings.json 我有一个这样的字段</p><pre> "MyFields": [ { "name":"one", "type":"type1" "parameters":[{"key":"url","value":"myurl.com"}, {"key":"data","value":"mydata"}] }, { "name":"two", "type":"type2"... .. and so on } ]</pre><p> 我制作了一个具有以下属性的 class Myfield:</p><pre> public class MyField { [JsonProperty] public string? name { get; set; } [JsonProperty] public string? type { get; set; } [JsonProperty] public IDictionary<string,string>? parameters { get; set; } }</pre><p> 我正在尝试使用配置在另一个 class 中访问它,如下所示:</p><pre> //config is the configuration var myFields = config.GetSection("MyFields").Get<List<MyField>>();</pre><p> 问题是 myFields 结果是空的。 但是当我通过消除“参数”字段来做同样的事情时,它就像一个魅力。</p><p> 我知道这与匹配不当有关,但能得到一些帮助会很棒。</p></div></object> 无法从appsettings.json读取数据 模型 .net 核心中 appsettings.json 的值 从1.0.0-rc1-final中的appsettings.json读取一个值 从 .net 核心中的 appsettings.json 获取价值 从 appsettings.json 中提取自定义数组 object 在控制台应用程序中从另一个 class 调用 appsettings.json 数据
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM