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

人气:449 发布:2022-10-16 标签: entity-framework asp.net-core-webapi asp.net-core-3.1

问题描述

我正在使用.NET核心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;"    
  }
}

我不确定需要对我的上下文类、上下文类进行哪些更改,如下所示:

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();
            }
        }

推荐答案

您不需要在您的数据库上下文类中执行任何操作,它是正确的

您应该这样调用数据库:

    //....
    private readonly pixelleContext _context;

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

    //....

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

838