簡體   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