繁体   English   中英

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

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

以下是我的 Web API 设置。

在 startup.cs 中,我添加了我的 DbContext class。

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

            ...
}

这是我的连接字符串

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

在 appsettings.json 文件中

然后我有 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);
            ...
        }
    }

我在存储库中注入这个 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);
        }
    }

最后将存储库注入 controller。 我正在使用 .net6,VS 2022。问题是在发出 API 请求时没有调用 OnModelCreating。 调用 AppDbContext 构造函数,但未调用方法 OnModelCreating。

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

你能帮我理解发生了什么变化吗? 我错过了什么?

哦,我不小心在旧版本上保留了两个包 - microsoft.entityframeworkcore.sqlserver 和 microsoft.entityframeworkcore.tools 没有迁移到版本 6.0.0。 我现在迁移它们并解决了问题。

暂无
暂无

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

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