How can I implement DbContext Connection String in .NET Core?
Generally you are going to want to read it from config at start-up, and then use the connection string to configure an Entity Framework DbContext service for your process.
1) Add a line to your appsettings.json:
"DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",
2) Read the line in you Startup.cs class (after the Startup method is called to build the Configuration - so usually in the ConfigureServices method) like this:
var connection = Configuration["DbConnectionString"];
3) If using Entity Framework add a database context service (MyDbContext is the context class generated by EF). You also want to tell the built-in dependency injection how to instantiate your database context:
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
services.AddScoped<IMyDbContext, MyDbContext>();
Where IMyDbContext is (at it's simplist) just an interface you've extracted from your MyDbContext
4) Now you can define your controller to take a MyDbContext and the DI will take care of building it and passing it in when the controller is invoked:
public MyController(IMyDbContext context)
{
_context = context // store for later use
}
Another option would be to call the base constructor that takes a DbContextOptions:
public BooksContext(string connectionString) : base(GetOptions(connectionString))
{
}
private static DbContextOptions GetOptions(string connectionString)
{
return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}
IMO best practice:
add to your configuration.json:
"ConnectionStrings": {
"BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
}
and to initialize section:
services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));