【问题标题】:OnModelCreating is not called when Entity Framework Core DbContext is used in Dependency Injection在依赖注入中使用 Entity Framework Core DbContext 时不调用 OnModelCreating
【发布时间】:2022-01-01 04:00:27
【问题描述】:

以下是我的 Web API 设置。

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

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 类

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);
        }
    }

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

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

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

【问题讨论】:

  • 我无法重现它(至少在我的设置中),但在极少数情况下,迁移时您可能会在另一个名称空间中留下另一个具有相同名称的类?如果不是,您可能必须创建一个全新的项目,看看是否仍然存在问题,然后将其发布到 Github 上,以便我们检查新项目中是否仍然存在。

标签: c# asp.net entity-framework-core dbcontext .net-6.0


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多