this is my appsettings.json
"ConnectionStrings": {
"Circolari": "Server=abcde;Database=Circolari;Trusted_Connection=True;"
}
and this is my startup.cs
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = configurationBuilder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//Circolari
string connectoionString = Configuration.GetConnectionString("Circolari");
services.AddDbContext<CircolariContext>(options => options.UseSqlServer(connectoionString));
services.AddMvc();
}
so when i do a query
using (CircolariContext db = new CircolariContext(new DbContextOptions<CircolariContext>()))
{
List<Argomenti> listaArgomenti = db.Argomenti.ToList();
}
i have the problem: An unhandled exception occurred while processing the request.
InvalidOperationException: A named connection string was used, but the name 'Circolari' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information.
Microsoft.EntityFrameworkCore.Storage.Internal.NamedConnectionStringResolverBase.ResolveConnectionString(string connectionString)
could someone help me please?
YouContextFile.cs add this code
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
// add IConfigurationRoot to get connection string
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"), x => x.UseNetTopologySuite());
}
}
Modify startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DB_A6136B_MiGranCitaContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MiGranCitaDB")));
then add the controller using the option API CONTROLLER WITH ACTIONS USING ENTITY FRAMEWORK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With