If we had a connection string stored into the appsettings.json file and we want to set our DbContext class to use this connection string, we need to call our DBContext constructor with che connection string parameter into the ConfigureService method of the class StartUp.cs.

For example, into the appsettings.json file we declare the connection string like the following:

"Data": { "DefaultConnection": { "ConnectionString": "Server=<SERVER_IP>\\<INSTANCE_NAME>;Initial Catalog=<DB_NAME>;Persist Security Info=False;User ID=<USER_NAME>;Password=<USER_PWD>" } }

So a valid connection string can be: “ConnectionString”: “Server=\\MSSQLSERVER;Initial Catalog=ExpertCodeBlog;Persist Security Info=False;User ID=Admin;Password=Admin#Pwd2018”.

On ExpertCodeBlogContext.cs (that with the other model class was automatically created by the Scaffold-DbContext command) we insert the constructor that accepts the connection string parameter:

public partial class ExpertCodeBlogContext : DbContext
{ public ExpertCodeBlogContext(DbContextOptions<ExpertCodeBlogContext> options) : base(options){ } // Other auto generated code omitted

On StartUp.cs, in the ConfigureService method, when we add the ExpertCodeBlogContext to the services, we can set the connection string like in the following example:

public IServiceProvider ConfigureServices(IServiceCollection services) { // Other code omitted // Set EntityFrameworkCore ExpertCodeBlogContext ConnectionString string connectionString = GetConnString(Configuration["Data:DefaultConnection:ConnectionString"]); services.AddDbContext<ExpertCodeBlogContext>(options => options.UseSqlServer(connectionString));

Laisser un commentaire