0

I have an ASP .NET MVC 6 and Entity Framework 6, divided into layers , how do I get the connection string in the DAL layer in my DbContext ? The connection string is in appsettings.json file like this:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "",
    }
  }
}
1
  • I guess you add an constructor with said parameters and push it through? Commented Mar 15, 2016 at 14:27

1 Answer 1

3

If you have the connection string in appsettings.json you want to build a configuration object first:

var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
var configuration = builder.Build();

This should probably be in Startup's ctor. You can then store the configuration object in a field. Let's say a _configuration field.

Then you can do

// _connectionString is also a field.
_connectionString = _configuration["Data:DefaultConnection"];

Your DbContext:

public class AppDbContext : DbContext
{
    public AppDbContext(string connectionString) : base(connectionString)
    {
    }
}

The you can register your AppDbContext in ConfigureServices as:

services.AddScoped(_ => new AppDbContext(_connectionString));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you , now how do I run the query in my repository class?
It should be easy from here, if you're using DI then simply request AppDbContext in your repository's ctor. After that, do your queries using AppDbContext as you always do. If you're just starting with either EntityFramework or Asp.Net Core then please tell us so that we know how to help you best.

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.