简体   繁体   中英

OnModelCreating is not called when Entity Framework Core DbContext is used in Dependency Injection

Following is my Web API setup.

in startup.cs, I am adding my DbContext class.

public void ConfigureServices(IServiceCollection services)
{
            services.AddDbContext<AppDbContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("DBConnection")));

            ...
}

Here is my connection string

"DBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true"

in appsettings.json file

Then I have DbContext class

public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
        {
        }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<Department> Departments { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            ...
        }
    }

And I am injecting this DbContext in the repository

public class EmployeeRepository : IEmployeeRepository
    {
        private readonly AppDbContext appDbContext;

        public EmployeeRepository(AppDbContext appDbContext)
        {
            this.appDbContext = appDbContext;
        }

        public async Task<Employee> GetEmployee(int employeeId)
        {
            return await appDbContext.Employees
                .FirstOrDefaultAsync(e => e.EmployeeId == employeeId);
        }
    }

And finally the repository is injected into the controller. I am using .net6, VS 2022. Problem is OnModelCreating is not getting called when API request is made. AppDbContext constructor is called but the method OnModelCreating is not called.

This was working for .net3.1 and VS 2019 but I just migrated to latest to use another library which is available only on latest versions.

Can you please help me understand what has changed? what am I missing?

Ohh, I accidently kept two of packages on old versions - microsoft.entityframeworkcore.sqlserver and microsoft.entityframeworkcore.tools was not migrated to version 6.0.0. I migrated them now and issue is resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM