.Net Core 2 EF core connection string problem
Asked Answered
D

4

6

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?

Disconcerted answered 5/10, 2018 at 6:49 Comment(25)
Are you sure your appSettings.json is being loaded? You've marked it as optional, so if env.ContentRootPath isn't the right folder, it won't be loaded. Try marking it as optional: false to see if it throws an exception.Surrey
Your example code for "so when I do a query" does not use dependency injection, is that the actual code generating the error? I wonder how the error is getting the connection string name "Circolari" if so...Scandent
@John i think that the configuration is loaded because if i put a breackpoint in ConfigureServices the string is readed, and with optional: false the error is still hereDisconcerted
@Scandent this is the actual code, the same i am writing in my little example for configuring ef core on .net coreDisconcerted
Use optional: false.Humorist
var connectoionString = Configuration.GetValue<string>("ConnectionStrings:Circolari"); is another way to get from configurationHumorist
@t-prisar if i use optional: false the problem persistDisconcerted
@Disconcerted Is there a chance that you're loading the wrong configuration file?Surrey
In ConfigureServices you have ˋUseSqlServer´ but in appsettings.json ˋServer=abcdé´?Smoking
@Scandent with var connection = Configuration.GetValue<string>("ConnectionStrings:Circolari"); the problem persistDisconcerted
@Smoking yes, the 'abcde' is a replaced string that , the correct is in appsetting.jsonDisconcerted
@John i think that i am loading the correct configuration file because in 'ConfigureServices' string connectoionString = Configuration.GetConnectionString("Circolari"); give me the correction connection stringDisconcerted
Why you are using the ˋIConfigureBuider´? What version of .Net core you are using?Smoking
@Smoking i use IConfigureBuilder because i think is the standard. Microsoft.AspNetCore.Mvc v2.1.3 Microsoft.AspNetCore v2.1.4Disconcerted
I think the IConfigureBuilder is used in .Net core 1.0. Check the docs for migration learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/…Smoking
@Smoking now my startup is empty and i iInject IConfiguration in Startup(IConfiguration configuration) but the problem is still thereDisconcerted
But if you really are calling new CircolariContext(new DbContextOptions<CircolariContext>()), it doesn't use your configurationHouseraising
Maybe you need to call directly without the string connectoionStringSmoking
See the Exception ˋA named connection string was used,´.Smoking
@IvanStoev i am using this code using (CircolariContext db = new CircolariContext()) { List<Argomenti> listaArgomenti = db.Argomenti.ToList(); }Disconcerted
@Smoking yes, but ef does not find .... and i dont know why...Disconcerted
I think you need to call just the ˋCircularí´ connectionstring like ˋUseSqlServer(Configuration.GetConnectionString("Circolari")));´Smoking
@Smoking i don't want to modify this file because is generated by Scaffold-DbContextDisconcerted
ˋstring connectoionString = Configuration.GetConnectionString("Circolari");´ is generated by Scaffold-DbContext??Smoking
@Llazar, no but optionsBuilder.UseSqlServer("Name=Circolari"); yes and i don't want to change code thereDisconcerted
U
8

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());
            }
        }
Ursula answered 15/5, 2020 at 14:57 Comment(1)
Adding this to my context has sorted my issue where I couldn't scaffold a new controller.Lochia
G
1

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

Gladisgladney answered 14/5, 2020 at 20:11 Comment(0)
D
0

Finally i found the solution to my problem:

now in asp.net core everything must be injected, so you can get yout db context via ServiceProvider (just like the compiler told me)

//this is the constructor
public EfGiacenzeRepo(IServiceProvider serviceProvider)
{
    _serviceProvider = serviceProvider;
}


//this is the method
using (_aspContext = _serviceProvider.GetService<aspContext>())
{
    listaGiacenze = _aspContext.TabGiacenza.ToList();
}
Disconcerted answered 24/10, 2018 at 10:5 Comment(0)
W
0

I was seeing the same error message, and none of the solutions here solved the issue for me.

My problem was that in my DEV environment, I have multiple projects selected as startup projects.

When that is the case, it seems that Visual Studio does not know where to look for the appsettings.json file.

Temporarily switching to a single startup project solves this issue, so I do this when I need to rebuild the database models with Scaffold-DbContext.

Wristwatch answered 12/5, 2021 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.