在EF Core中创建DbContext实例时如何传递DbContextOptions值

时间:2019-06-16 19:45:45

标签: c# asp.net-core entity-framework-core

我正在尝试从appSettings.json文件中获取连接字符串,但是我不能。

我的创业公司是这样:

namespace YangSoft_WebAPI
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional:false, reloadOnChange:true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:true)
                .AddEnvironmentVariables();

            Configuration = builder.Build();
            var enviroment = Configuration["ApplicationSettings:Enviroment"];

        }
        readonly string AllowControlOrigins = "Access-Control-Allow-Origin";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettingsDAL>(Configuration.GetSection("ApplicationSettings"));
            services.AddDbContextPool<yangsoftDBContext>(options =>
                     options.UseSqlServer(Configuration.GetConnectionString("local")));
            services.AddCors(options =>
            {

                options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("*");
                });

                options.AddPolicy(AllowControlOrigins,
                builder =>
                {
                    builder.WithOrigins("http://localhost:3000",
                                        "https://localhost:3000", 
                                        "http://yangsoft-frontend.s3-website.us-east-2.amazonaws.com")
                                        .AllowAnyHeader()
                                        .AllowAnyMethod();
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Test API",
                    Description = "ASP.NET Core Web API"
                });
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseCors(AllowControlOrigins);
            app.UseHttpsRedirection();
            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUI(c => {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API V1");
            });
        }
    }
}


在我的启动中,如何看待我初始化DBContext,在mi DBLogic中我有以下内容:

public partial class yangsoftDBContext : DbContext
{
    private readonly AppSettingsDAL _appSettings;

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

    public virtual DbSet<Acceso> Acceso { get; set; }
    public virtual DbSet<Actividad> Actividad { get; set; }
    public virtual DbSet<Auditoria> Auditoria { get; set; }

    ......................

}

这是webLogic中我的合作伙伴类中DAL的示例方法:

public int CountActiveSocios()
{
   using (var context = new yangsoftDBContext())
   {
      try
      {
          return context.Socios.Where(r => r.Estado == true).Count();
      }
      catch
      {
          return 0;
      }

    }
}

在我称之为youngsoft DBContext .net的所有地方返回此错误:

  

““没有参数,因为它对应于所需的形式参数'options'””

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

public int CountActiveSocios()
{
   IConfiguration configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

   var connectionString = configuration.GetConnectionString("local");

   var options = new DbContextOptionsBuilder<yangsoftDBContext>()
                    .UseSqlServer(new SqlConnection(connectionString))
                    .Options;

    using (var context = new yangsoftDBContext(options)) // <-- Pass the options here
    {
       try
       {
           return context.Socios.Where(r => r.Estado == true).Count();
       }
       catch
       {
          return 0;
       }

    }
}

要重用DbContextOptions,可以编写如下的帮助方法:

public static class DbContextHelper
{
    public static DbContextOptions<yangsoftDBContext> GetDbContextOptions()
    {
        IConfiguration configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();


      return new DbContextOptionsBuilder<yangsoftDBContext>()
            .UseSqlServer(new SqlConnection(configuration.GetConnectionString("local"))).Options;

    }
}

然后使用如下:

public int CountActiveSocios()
{
    var dbContextOptions = DbContextHelper.GetDbContextOptions();

    using (var context = new yangsoftDBContext(dbContextOptions)) // <-- Pass the options here
    {
       try
       {
           return context.Socios.Where(r => r.Estado == true).Count();
       }
       catch
       {
          return 0;
       }

    }
}