【问题标题】:IDesignTimeDbContextFactory not always needed?IDesignTimeDbContextFactory 并不总是需要?
【发布时间】:2018-02-22 11:28:37
【问题描述】:

以前我必须实现 IDesignTimeDbContextFactory 才能运行迁移,例如: PM > 添加-迁移初始 PM > 更新数据库

如果没有,控制台会报错并把我带到这里:https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext#use-idesigntimedbcontextfactory

所以我按照它的建议进行操作并运行迁移。 之后我创建了新项目,我不必实现 IDesignTimeDbContextFactory。无论如何,迁移都奏效了。这怎么可能? 所有项目都使用相同的 .NET Core 版本 (2.0)。

我们是否总是需要创建 IDesignTimeDbContextFactory,还是只是在某些情况下才需要?

谢谢!

【问题讨论】:

  • 这适用吗? bountysource.com/issues/…
  • 谢谢,我在 github 上找到了讨论,所以我也会在那里发布问题,并在收到回复后回复。

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


【解决方案1】:

好的,那就这样吧: 如果您在 DbContext 中有默认构造函数或使用在 ASP.NET Core 2.0 项目模板中建立的 Program.BuildWebHost() 模式,则通常不需要 IDesignTimeDbContextFactory 实现。

在 2.0.0-preview1 中,未使用 Program.BuildWebHost(),您需要一个设计时工厂。

完整讨论请参见此主题: https://github.com/aspnet/EntityFrameworkCore/issues/9033

【讨论】:

    【解决方案2】:

    正如 Dan Banan 所说,如果 DbContext 具有默认构造函数,则在设计时将不需要 IDesignTimeDbContextFactory。但是,如果需要从Startup 进行配置,则需要一个构造函数来接受DbContextOptions<T> 并调用相应的base 构造函数。但是,这将产生另一个问题。无论使用哪个构造函数,都会调用DbContextOnConfigure 方法。

    为了说明这些细节,我发现以下模式很有用:

    DbContext 配置和依赖注入

    serviceCollection
        .AddDbContext<MyDbContext>(
            options => options.UseSqlServer(configuration.GetConnectionString("MyDb"),
            ServiceLifetime.Transient
        );
    

    MyDbContext.cs

    public class MyDbContext : DbContext
    {
        public SureshotDbContext()
        {
            // This allows for instantiation at design time.
        }
    
        public MyDbContext(DbContextOptions<MyDbContext> options) :
            base(options)
        {
            // This allows for configuration in real applications.
        }
    
        protected override void OnConfiguring(
            DbContextOptionsBuilder optionsBuilder
        )
        {
            if (optionsBuilder.IsConfigured)
            {
                return;
            }
    
            optionsBuilder.UseSqlServer(nameof(TDbContext));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-21
      • 2013-03-08
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多