This error means you have created the DbContext but not configured/added it to the project using either DI in startup.cs or by using DbContext.OnConfiguring method.
Add DbContext in starup.cs or configure it by overriding the virtual DbContext.OnConfiguring method.
============================================================
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server=.;database=myDb;trusted_connection=true;");
}
NOTE to use connectionString from appsetting.json. follow these steps:
1. In appsettings.json add ConnectionStrings section below allowedhosts and add a name-value pair for connection string.
2. Inject IConfiguration in DbContext constructor. You will need to add "using Microsoft.Extensions.Configuration" statement for this.
3. You can now get the conn string by using configuration.GetConnectionString("name");
public class EmployeeContext : DbContext
{
private readonly IConfiguration configuration;
public DbSet<Employee> Employees { get; set; }
public EmployeeContext(IConfiguration configuration)
{
this.configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string str = configuration.GetConnectionString("conn");
optionsBuilder.UseSqlServer(str);
}
}
===================================================================================
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>(options => {
options.UseSqlServer("server=.;database=myDb;trusted_connection=true;"));
});
}
OR
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<EmployeeContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("conn")));
}
NOTE that once you configure DbContext in ConfigureServices, you must wire it with DbContext by using a constructor that takes DbContextOptions as parameter and passes it to base contructor.
public class EmployeeContext : DbContext
{
public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options)
{
}
DbSet<Employee> Employees { get; set; }
}
===================================================================================
No comments:
Post a Comment