✅ Layered architecture EF Core error when creating migrations
I have a Web Api project which is using .NET Core 7, my layers are DAL, Services Entities and API. I recently moved connection string to appsettings.json file (it was hardcoded in my appdbcondext class before) and created a extension method in DAL layer which sets connection string, I am using this in my startup project (API) program.cs but when I run
dotnet ef migrations add testMig
dotnet ef migrations add testMig
it gives an error
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
It was not happening when I hard code connection string in DAL layer and add/update migrations,
ApplicationDbContext.cs (DAL)
namespace MeetingAppDemo.DAL.Context{ public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } public DbSet<User> Users { get; set; } public DbSet<Meeting> Meetings { get; set; } public DbSet<MeetingParticipant> MeetingParticipants { get; set; } public DbSet<MeetingDocument> MeetingDocuments { get; set; } }}
namespace MeetingAppDemo.DAL.Context{ public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } public DbSet<User> Users { get; set; } public DbSet<Meeting> Meetings { get; set; } public DbSet<MeetingParticipant> MeetingParticipants { get; set; } public DbSet<MeetingDocument> MeetingDocuments { get; set; } }}
DataAccessExtension.cs (DAL)
namespace MeetingAppDemo.DAL.Extensions{ public static class DataAccessExtensions { public static IServiceCollection SetupDbContext(this IServiceCollection services, string connectionString) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); return services; } }}
namespace MeetingAppDemo.DAL.Extensions{ public static class DataAccessExtensions { public static IServiceCollection SetupDbContext(this IServiceCollection services, string connectionString) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); return services; } }}