From 9a48fb80723d0aa5fabc52b88f2acbcc63ada67d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=B1=E6=95=AC=E9=91=AB=28=E6=B5=B4=E7=9A=87=E5=A4=A7?= =?UTF-8?q?=E5=B8=9D=E7=89=88=29?= <3284280335@qq.com> Date: Mon, 9 Dec 2024 17:43:48 +0800 Subject: [PATCH] =?UTF-8?q?20241209-=E5=BA=94=E7=94=A8EntityFrameworkCore?= =?UTF-8?q?=E7=9A=84=E6=AD=A5=E9=AA=A4=E7=AC=94=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...re\347\232\204\346\255\245\351\252\244.md" | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 "\346\234\261\346\225\254\351\221\253/\350\257\276\345\240\202\347\254\224\350\256\260/20241209-\345\272\224\347\224\250EntityFrameworkCore\347\232\204\346\255\245\351\252\244.md" diff --git "a/\346\234\261\346\225\254\351\221\253/\350\257\276\345\240\202\347\254\224\350\256\260/20241209-\345\272\224\347\224\250EntityFrameworkCore\347\232\204\346\255\245\351\252\244.md" "b/\346\234\261\346\225\254\351\221\253/\350\257\276\345\240\202\347\254\224\350\256\260/20241209-\345\272\224\347\224\250EntityFrameworkCore\347\232\204\346\255\245\351\252\244.md" new file mode 100644 index 0000000..d29d228 --- /dev/null +++ "b/\346\234\261\346\225\254\351\221\253/\350\257\276\345\240\202\347\254\224\350\256\260/20241209-\345\272\224\347\224\250EntityFrameworkCore\347\232\204\346\255\245\351\252\244.md" @@ -0,0 +1,34 @@ +1. 安装依赖包,命令:`dotnet add package Microsoft.EntityFrameworkCore.SqlServer` +2. 安装项目的命令包`dotnet add package Microsoft.EntityFrameworkCore.Design` +3. 定义数据库表模型 +```c# +namespace Blog.Models; + +public class Blogs +{ + public int Id { get; set; } + public string Title { get; set; } = null!; + public string Content { get; set; } = null!; + public string Author { get; set; } = null!; +} +``` +4. 定义数据库上下文 +```C# +using Microsoft.EntityFrameworkCore; + +namespace Blog.Models; + +public class BlogDbContext : DbContext +{ + public DbSet Blogs { get; set; } = null!; + + + // The following configures EF to create a Sqlite database file in the + // special "local" folder for your platform. + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlServer($"Server=.\\SQLEXPRESS;database=XiaoZhu;uid=sa;pwd=123456;TrustServerCertificate=True;"); +} +``` +5. 生成迁移文件,命令:```dotnet ef migrations add XXX (PS:可能需要安装如下依赖包:Microsoft.EntityFrameworkCore.Design)``` + +6. 将上一步生成的迁移文件,更新到数据库:`dotnet ef database update`(PS:需要保证连接字符串正确无误,包括用户名、密码等,数据库打开,并且允许远程连接) \ No newline at end of file -- Gitee