问题
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