entity framework core在独立类库下执行迁移操作

时间:2023-03-09 09:21:45
entity framework core在独立类库下执行迁移操作

之前学习EFCore的时候,都是在VS创建的默认模板里面进行的,按照官方文档,直接就可以搞定。

今天新项目准备上.Net Core,打算先按照国际惯例,进行分层,数据访问层是用EFCore来做,于是就单独把这层放到一个类库里面

1.添加引用

entity framework core在独立类库下执行迁移操作

第二个和第三个库是必须要添加的,如果你不用命令迁移除外。。。。。

2.打开程序包管理控制台

Add-Migration intidb

然后就会发现报错了

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

大致意思就是找不到数据库连接,因为按照正常情况下,我们的数据库连接会在StartupConfigureServices里面读取,但是独立的类库执行命令的时候,是不会执行到Startup命令的。

找到原因就好办了,重写一下DbContextOnConfiguring方法

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
"Data Source=.;Initial Catalog=dbname;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=123456");
}

然后重新执行

Add-Migration intidb

然后执行

Update-Database -Verbose

打开数据库就能看到EFCore自动生成的数据库了