需要在上下文 class 中进行哪些更改才能将连接字符串移动到 appsettings.json 文件中

What changes need to be made in context class to move connection string into appsettings.json file

我正在使用 .NET CORE WEB API 项目,我正在尝试将我的连接字符串移动到 appsettings.json 文件。

为此,我做了以下更改:

在启动文件中:

public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddCors(options =>
            {
                options.AddPolicy(allowSpecificOrigins,
                builder =>
                {
                    builder.AllowAnyOrigin()
                            .AllowAnyHeader()
                            .AllowAnyMethod();
                });
            });
services.AddSingleton(provider => Configuration);
            services.AddDbContext<pixelleContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("PixelleConnection")));
        }

和 appsettings.json 文件如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "PixelleConnection": "Server=localhost;Database=PixelleSpecSheets;Trusted_Connection=True;"    
  }
}

我不确定我需要在上下文 class 中做哪些更改,上下文 class 如下:

public partial class pixelleContext : DbContext
    {
        public pixelleContext()
        {
        }

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

        public virtual DbSet<SpecCol> SpecCol { get; set; }
        public virtual DbSet<SpecRow> SpecRow { get; set; }
        public virtual DbSet<Specsheet> Specsheet { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                

              
            }
        }
}

和抛出错误的代码:

[System.Web.Http.HttpGet]
        public IEnumerable<Specsheet> Get()
        {
            using (var context = new pixelleContext())
            {
                return context.Specsheet.ToList();
            }
        }

您不需要在您的 dbcontext 中做任何事情class,这是正确的

你应该这样调用数据库:

    //....
    private readonly pixelleContext _context;

    public ****Controller(pixelleContext context)
    {
        _context = context;
    }

    //....

    [HttpGet]
    public IEnumerable<Specsheet> Get()
    {
        var model = _context.Specsheet.ToList();
        return model;
    }