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

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

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

1.添加引用

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

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");
        }

 

然后重新执行

1
Add-Migration intidb

然后执行

1
Update-Database -Verbose

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

 

posted on   快乐海盗  阅读(398)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示