How to pass DbContextOptions value while creating DbContext instance in EF Core

asp.net-core c# entity-framework-core

Question

I'm trying to get the connection string from appSettings.json file but i can't.

My startup is this:

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


in my startup how can you see, i initialize the DBContext, after in mi DBLogic i have this:

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

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

}

And here is an example method in my partner class at webLogic into DAL:

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

    }
}

In all places that I call youngsoft DBContext .net returns this error:

"there is no argument given thats correspond to the required formal parameter 'options'"

1
0
6/17/2019 3:10:54 AM

Accepted Answer

You can do as follows:

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

    }
}

To reuse the DbContextOptions you can write an helper method as follows:

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;

    }
}

Then use as follows:

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

    }
}
2
6/17/2019 3:05:34 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow