Home > other >  How can I get connectionstring from appsetting using ConfigurationManager?
How can I get connectionstring from appsetting using ConfigurationManager?

Time:09-30

I created a asp.net core web api project that has Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Tools, and System.Configuration.ConfigurationManager. I ran the Scaffolding command Scaffold-DbContext "Data Source=DEX-LEP3LOXH0M5\\SQLEXPRESS;Initial Catalog=LibraryStore;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models.

In Context.cs file that was created from the scaffolding cmd created this method:

 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. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                 optionsBuilder.UseSqlServer("Data Source=DEX-LEP3LOXH0M5\\SQLEXPRESS;Initial Catalog=LibraryStore;Integrated Security=True");
               
            }
        }

when I ran the route path to the controller it worked perfectly I was able to see the records from the DB. But on that #warning message, it provided a link which I followed. In my appsettings.json file I added ConnectionStrings by doing:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Default": "Data Source=DEX-LEP3LOXH0M5\\SQLEXPRESS;Initial Catalog=LibraryStore;Integrated Security=True"
  }
}

then my next step was to add the code in the ConfigureServices in the startup.cs:

public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "LibraryWebAPI", Version = "v1" });
            });
            services.AddDbContext<LibraryStoreContext>(options =>
                  options.UseSqlServer(Configuration.GetConnectionString("Default")));
        }

then it said to change the OnConfiguring() in the Context.cs file that was created.

I did the following:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                
                optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["Default"].ConnectionString);
            }
        }

but then it generates the error message on the line optionsBuilder:

System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.

Is there a reason why it is returning null if the same connection string worked before following the link to add connection to connectionstring in appsettings?


including my controlller:

        [HttpGet]
        [Route("GetAllDetails")]
        public IEnumerable<LibraryInfo> GetDetails()
        {
            using (var context = new LibraryStoreContext())
            {
                // get all library details
                return context.LibraryDetails.ToList();
            }
        }

CodePudding user response:

The .Net Core application uses appsettings.json instead of web.config file.

Because .Net Core applications are self hosted and can almost run on any platform, they are no longer have to be hosted on IIS. The .Net Core application settings are stored in a Json format (appsettings.json) by default while .Net Framework application configurations are stored in a web.config file in XML format This is why it shouldn't work with your appsettings.json when using ConfigurationManager

From the guid you sent they say to do the change in protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

But this is said not on .net core applications

CodePudding user response:

I did just find a more comfortable way to maintain generating migrations, where you don't have to run the command from the web project.

DbContext

internal class ContosoContext : DbContext
{
    private readonly IConfiguration configuration;
    public ContosoContext(IConfiguration configuration)
    {
        this.configuration = configuration;
    }
    public ContosoContext()
    {
        this.configuration = null;
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        if (configuration == null)
        {
            // Only used when generating migrations
            // Contoso.Data = name of the project where your migrations should reside
            var migrationsConnectionString = @"Server=(localdb)\mssqllocaldb;Database=Contoso;Trusted_Connection=True;ConnectRetryCount=0";
            optionsBuilder.UseSqlServer(migrationsConnectionString, options => options.MigrationsAssembly("Contoso.Data"));
        }
        else
        {
            optionsBuilder.UseSqlServer(configuration.GetConnectionString("Contoso"));
        }
    }
}

Registration of the DbContext

services.AddDbContext<ContosoContext>(options => {
   options.UseSqlServer(Configuration.GetConnectionString("Contoso"));
});
  • When running the application (the web project), the constructor with parameters will be called.
  • When generating migrations from the Contoso.Data folder (dotnet ef migrations add myawesomemigration), the parameterless constructor will be called.

This drops the need of excessively specifying paramters during the generation of database migrations:

dotnet ef migrations add AddIdentity
  • Related