I have a problem with the connection string that sits inside the json configuration file , as usual :
- i have created a class : applicationDbcontext
- i made a DbSet {get;set;}
- integrate it into the controller
- add it to the services
I have read and try all the advices inserted in the related question : asp.net core 2.0 - Value cannot be null. Parameter name: connectionString But none of them works with me Here is my implementation , I hope someone can help me , thank you
A_ DB Context :
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
Database.EnsureCreated();
}
public DbSet<Person> Persons { get; set; }
}
}
B_ App Settings :config.json and config.development.json
{
"ConnectionString": {
"testConnection": "Server=(localdb)\\mssqllocaldb;Database=mvc_db;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
C_ Services Injection
Startup :
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.Json")
.AddJsonFile("appsettings.Development.Json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
Configuration Services :
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("testConnection"));
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
D_ Injection Into Controllers :
private readonly ApplicationDbContext _db;
public PersonController(ApplicationDbContext db)
{
_db = db;
}
IEnumerable<Person> People { get; set; }
public IActionResult Index()
{
People = _db.Persons.ToList();
return View(People);
}
I have tried to insert the whole connectionString inside the configuration.GetConnectionString("Here");
And To change the location of the connection string from up to down and vice verse.
But nothing fix the return null value problem of the connectionString .
Any Help please Thanks