I'm trying to run a migration to create my initial database from code, but i'm having difficulties with proper registration of DbContextOptions.
My program.cs contains the service registration:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Registering the DbContext
var connectionString = builder.Configuration.GetConnectionString("EduSqlServer");
builder.Services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(connectionString, b => b.MigrationsAssembly("data_access_layer")));
Note: program.cs is in the education.Server assembly.
Appsettings.json:
"ConnectionStrings": {
"EduSqlServer": "Server=.;Database=EduDb;Trusted_Connection=True;Encrypt=False"
},
I have a different assembly called "data_access_layer" where i have my DbContext.
Here's ApplicationDbContext.cs:
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :
base(options)
{
}
When running the 'Add-Migration CreateDb' command in my package manager console I'm getting an error:
Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[data_access_layer.Domain.Context.ApplicationDbContext]' while attempting to activate 'data_access_layer.Domain.Context.ApplicationDbContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
I noticed that if i create an empty constructor for my ApplicationDbContext and in the OnConfiguring method of ApplicationDbContext i place the exact same code that i did have in my program.cs than i can create a migration.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ optionsBuilder.UseSqlServer("Server=.;Database=EduDb;Trusted_Connection=True;Encrypt=False", b => b.MigrationsAssembly("data_access_layer"));
}
This works for now, but i obviously don't want to hardcode my sql server's connection string for my final application. I'd like for it to work through proper service resolve. How could i fix this issue?
I was trying to follow: https://zcusa.951200.xyz/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-8.0
but wanted to use sql server instead of in-memory database.