.Net Core 2 EF core connection string problem

回眸只為那壹抹淺笑 提交于 2020-12-13 03:41:28

问题


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?


回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/52659818/net-core-2-ef-core-connection-string-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!