如何实现IDbContextFactory以用于Entity Framework数据迁移

Tim*_*ter 43 data-migration entity-framework

我试图使用实体框架数据迁移,如描述的这个帖子.

但是,当我尝试执行该Enable-Migrations步骤时,我在程序包管理器控制台中收到以下错误:

The target context 'MyDataContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory
Run Code Online (Sandbox Code Playgroud)

因此,我创建了一个IDbContextFactory在包含我的DbContext类的项目中实现的工厂类,但数据迁移似乎无法识别它.

我是否应该明确指示数据迁移使用此工厂类?

dou*_*ald 59

当我编写我的上下文以获取连接字符串名称(然后使用ninject提供它)时,我也遇到了这个问题.

你经历过的过程似乎是正确的,如果它有任何帮助,这里是我的类实现的片段:

public class MigrationsContextFactory : IDbContextFactory<MyContext>
{
    public MyContext Create()
    {
        return new MyDBContext("connectionStringName");
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该就是你所需要的.

  • EF如何了解工厂类的存在 - MigrationsContextFactory.我们不是必须在某处注册它以便框架知道吗?这个班级是否独立自给自足?蒂姆似乎也承认它不会被要求! (9认同)
  • 你能提供Ninject配置代码吗?我不明白我将注入connectionStringName的位置,因为Create不接受构造函数参数. (8认同)
  • 仅供参考 [IDbContextFactory](https://docs.microsoft.com/en-gb/dotnet/api/microsoft.entityframeworkcore.infrastructure.idbcontextfactory-1?view=efcore-2.1) 现在已过时。改用 [IDesignTimeDbContextFactory](https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.design.idesigntimedbcontextfactory-1?view=efcore-2.1)。 (4认同)
  • 你把这门课放在哪里了? (2认同)