【问题标题】:Entity Framwork Core Add-Migration fails实体框架核心添加迁移失败
【发布时间】:2019-02-25 20:19:17
【问题描述】:

我正在尝试在我的项目中使用 Ef Core。

结构有点不同,因为我没有在 WebApi.csproj 中使用 EfCore。事实上我有一个不同的dll。和一个 DependenciesResolver.dll 来处理我所有的依赖注入。

在我的 EfCore.dll 中我都安装了

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.SqlServer

现在当我尝试运行命令时(我正在运行的 dll 是 EfCore.dll)

Add-Migration Name

我明白了:

访问“程序”类上的 IWebHost 时出错。 在没有应用程序服务提供商的情况下继续。错误:对象 引用未设置为对象的实例。无法创建 “StoreContext”类型的对象。添加一个实现 'IDesignTimeDbContextFactory' 到项目中,或参见 https://go.microsoft.com/fwlink/?linkid=851728 更多模式 在设计时支持。

sln的结构是这样的

WebApi | EfCore.dll | DependencyResolver.dll,我想保持这种方式,不想允许在我的 WebApi 中使用 EfCore。

这个问题的解决方法是什么?

如果这对 EfCore.dll 有帮助,我有这个。

 public sealed partial class StoreContext : DbContext, IStoreContext
    {
        private string _connectionString;

        public StoreContext(string connectionString) : base()
        {
            _connectionString = connectionString;

            Database.EnsureCreated();
        }

        /// db.tbls
        public DbSet<Order> Orders { get; set; }

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

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(_connectionString);
        }
    }

像这样被DependencyResolver调用

        private DependenciesResolver RegisterInfrastructure()
        {
            _serviceCollection.AddScoped<StoreContext>(factory => new StoreContext(_connectionString));

            return this;
        }

然后WebApi调用DependencyResolver

【问题讨论】:

    标签: c# .net-core entity-framework-core asp.net-core-2.0 ef-core-2.1


    【解决方案1】:

    请看这个:https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation

    错误消息明确指出 EF Core 工具无法在设计时创建 Context 的实例。

    如果您可以为您的 StoreContext 定义一个不带参数的构造函数,那么您需要通过定义一个实现 IDesignTimeDbContextFactory 接口的类来告诉工具如何在设计时创建上下文的实例。

    【讨论】:

      猜你喜欢
      • 2018-11-17
      • 2020-06-21
      • 2021-06-27
      • 2020-05-30
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多