locked
DataBase Connection In appsettings.json RRS feed

  • Question

  • User974100899 posted

    I am having trouble with my database conneciton.  I've set-up appsettings.json to read like this

    {
      "ConnectionStrings": {
        "DB": "Server=server;Database=DB;User Id=auseraccount; Password=apassword;"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*"
    }

    And my startup.cs looks like this...

    public class Startup
    {
    	public Startup(IConfiguration configuration)
    	{
    		Configuration = configuration;
    	}
    
    	public IConfiguration Configuration { get; }
    	
    	public void ConfigureServices(IServiceCollection services)
    	{
    		services.AddDbContext<TapCountContext>(options =>
    			options.UseSqlServer(Configuration.GetConnectionString("DB")));;
    
    		services.Configure<CookiePolicyOptions>(options =>
    		{
    			options.CheckConsentNeeded = context => true;
    			options.MinimumSameSitePolicy = SameSiteMode.None;
    		});
    
    
    		services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    	}
    
    	public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    	{
    		if (env.IsDevelopment())
    		{
    			app.UseDeveloperExceptionPage();
    		}
    		else
    		{
    			app.UseExceptionHandler("/Home/Error");
    			app.UseHsts();
    		}
    
    		app.UseHttpsRedirection();
    		app.UseStaticFiles();
    		app.UseCookiePolicy();
    
    		app.UseMvc(routes =>
    		{
    			routes.MapRoute(
    				name: "default",
    				template: "{controller=Home}/{action=Index}/{id?}");
    		});
    	}
    }

    Now when I try to run the MVC app, I get this error message:

    AddDbContext was called with configuration, but the context type 'TapCountContext' only declares a parameterless constructor. This means that the configuration passed to AddDbContext will never be used. If configuration is passed to AddDbContext, then 'TapCountContext' should declare a constructor that accepts a DbContextOptions<TapCountContext> and must pass it to the base constructor for DbContext

    On this line of code:

    services.AddDbContext<TapCountContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DB")));;

    Which I understand is telling me that TapCountContext needs a constructor with parameters.

    I tried to add in this code:

    public DbSet(DbContextOptions<TapCountModel> builderOptions) : base(builderOptions)
    {
    
    }

    But I get these 3 build errors of:

    Method must have a return type.

    The type 'WebApplication2.Models.TapCountModel' cannot be used as type parameter 'TContext' in the generic type or method 'DbContextOptions<TContext>'. There is no implicit reference conversion from 'WebApplication2.Models.TapCountModel' to 'Microsoft.EntityFrameworkCore.DbContext'.

    There is no argument given that corresponds to the required formal parameter 'builderOptions' of 'TapCountContext.TapCountContext(DbContextOptions<TapCountModel>)'

    What do I need to change so that I can use the DBConnection that i set-up in my appsettings.json?

    Friday, October 11, 2019 5:26 AM

Answers

  • User1120430333 posted

    This was is in the startup.cs.

    services.AddDbContext<PublishingCompanyContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

    In the context class, I changed the code using DbContextOptions on the constructor and commented out optionsBuilder.UseSqlServer line. 

    public partial class PublishingCompanyContext : DbContext
        {
            public PublishingCompanyContext(DbContextOptions<PublishingCompanyContext> options)
                : base(options)
            {
            }
    
            public virtual DbSet<Article> Article { get; set; }
            public virtual DbSet<Author> Author { get; set; }
            public virtual DbSet<Payroll> Payroll { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
              //      optionsBuilder.UseSqlServer(new AppConfiguration(_options).GetPublishingCompanyConn());
                }
            }

    https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

    <copied>

    The DbContextOptions can be supplied to the DbContext by overriding the OnConfiguring method or externally via a constructor argument.
    If both are used, OnConfiguring is applied last and can overwrite options supplied to the constructor argument.

    <end>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 11, 2019 7:52 AM

All replies

  • User-1558406524 posted

    Try adding this in your DbContext File.

     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
    #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                    optionsBuilder.UseSqlServer("Server=server;Database=DB;User Id=auseraccount; Password=apassword;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;");
                }
            }

    Or get Connection string from DB and then use the same as you have done in startup.

    Friday, October 11, 2019 7:12 AM
  • User1120430333 posted

    This was is in the startup.cs.

    services.AddDbContext<PublishingCompanyContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

    In the context class, I changed the code using DbContextOptions on the constructor and commented out optionsBuilder.UseSqlServer line. 

    public partial class PublishingCompanyContext : DbContext
        {
            public PublishingCompanyContext(DbContextOptions<PublishingCompanyContext> options)
                : base(options)
            {
            }
    
            public virtual DbSet<Article> Article { get; set; }
            public virtual DbSet<Author> Author { get; set; }
            public virtual DbSet<Payroll> Payroll { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
              //      optionsBuilder.UseSqlServer(new AppConfiguration(_options).GetPublishingCompanyConn());
                }
            }

    https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

    <copied>

    The DbContextOptions can be supplied to the DbContext by overriding the OnConfiguring method or externally via a constructor argument.
    If both are used, OnConfiguring is applied last and can overwrite options supplied to the constructor argument.

    <end>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 11, 2019 7:52 AM