简体   繁体   English

在依赖注入中使用 Entity Framework Core DbContext 时不调用 OnModelCreating

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

Following is my Web API setup.以下是我的 Web API 设置。

in startup.cs, I am adding my DbContext class.在 startup.cs 中,我添加了我的 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在 appsettings.json 文件中

Then I have DbContext class然后我有 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我在存储库中注入这个 DbContext

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.最后将存储库注入 controller。 I am using .net6, VS 2022. Problem is OnModelCreating is not getting called when API request is made.我正在使用 .net6,VS 2022。问题是在发出 API 请求时没有调用 OnModelCreating。 AppDbContext constructor is called but the method OnModelCreating is not called.调用 AppDbContext 构造函数,但未调用方法 OnModelCreating。

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.这适用于 .net3.1 和 VS 2019,但我刚刚迁移到最新版本以使用仅在最新版本上可用的另一个库。

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.哦,我不小心在旧版本上保留了两个包 - microsoft.entityframeworkcore.sqlserver 和 microsoft.entityframeworkcore.tools 没有迁移到版本 6.0.0。 I migrated them now and issue is resolved.我现在迁移它们并解决了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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