EFcore迁移报错:“Unable to create an object of type ‘MyDbContext‘. For the different patterns supported ”

我们在输入迁移命令 Add-Migration  init 后发生错误!

EFcore迁移报错:“Unable to create an object of type ‘MyDbContext‘. For the different patterns supported ”_第1张图片

错误的原因我就不说了,直接上解决方法!

第一步:先创建一个DbContextDesignTimeFactory类

EFcore迁移报错:“Unable to create an object of type ‘MyDbContext‘. For the different patterns supported ”_第2张图片

 第二步:继承IDesignTimeDbContextFactory在<>中写入自己的Dbcontext,

并实现改接口

EFcore迁移报错:“Unable to create an object of type ‘MyDbContext‘. For the different patterns supported ”_第3张图片

 第三步:在接口实现的方法中配置连接数据库的代码(本案例是.net6的配置如有差异请微改)

EFcore迁移报错:“Unable to create an object of type ‘MyDbContext‘. For the different patterns supported ”_第4张图片

现在我们在来写迁移命令(记得把原来的Remove

已经不报错了,在执行Update-Database就完成迁移了

EFcore迁移报错:“Unable to create an object of type ‘MyDbContext‘. For the different patterns supported ”_第5张图片 

 

全部实现代码如下:

 /// 
    /// 1.写一个类
    /// 2.实现IDesignTimeContextFactory接口
    /// 3.返回Dbcontext类就行了
    /// 
    public class DbContextDesignTimeFactory : IDesignTimeDbContextFactory
    {
        public MyDbContext CreateDbContext(string[] args)
        {
           DbContextOptionsBuilder builder= new DbContextOptionsBuilder();
            builder.UseSqlServer("server=.;Database=IdentityDay1; user id=sa; Password=123456");
            return new MyDbContext(builder.Options);
        }
    }

你可能感兴趣的:(.netcore,c#)