3

I have a problem with the connection string that sits inside the json configuration file , as usual :

  1. i have created a class : applicationDbcontext
  2. i made a DbSet {get;set;}
  3. integrate it into the controller
  4. 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 Thanksenter image description here

1
  • The default set-up provided include the type when declaring the parameters in the ApplicationDBContext constructor public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } Not sure it would change much, but something i noticed that was different Commented Oct 5, 2018 at 23:52

2 Answers 2

6

Use this structure for the connectionString

 {

 "ConnectionStrings": {
  "DefaultConnection": "xxx"
   }
}

Check the json file you missed the s it should be ConnectionStrings

And Access Your Connection String in this simple way

   services.AddDbContext<ApplicationDbContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

In your case DefaultConnection should be testConnection

Sign up to request clarification or add additional context in comments.

4 Comments

Good spot on the property name but the name of the connection string does not have to be DefaultConnection.
excellent my friend the connectionString should be plural ... but the name can be what ever you want
Hello. In which file is the "ConnectionStrings": { written?
@ValterEkholm in appsettings.json file.
0

I have tried to insert the whole connectionString inside the configuration.GetConnectionString("Here");

But did you try changing:

options.UseSqlServer(Configuration.GetConnectionString("testConnection"));

to

options.UseSqlServer("your connection string");

Also, you mentioned you have config.json and config.development.json, but they should be appsettings.json and appsettings.development.json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.