From b9baecda2f0d1742b32cec731314e7989b08d141 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BD=95=E7=B4=AB=E6=82=A6?= <3418489566@qq.com> Date: Sun, 15 Dec 2024 20:53:37 +0800 Subject: [PATCH] zy --- ...346\215\256\345\272\223\344\270\216mvc.md" | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 "\344\275\225\347\264\253\346\202\246/20241213-\346\225\260\346\215\256\345\272\223\344\270\216mvc.md" diff --git "a/\344\275\225\347\264\253\346\202\246/20241213-\346\225\260\346\215\256\345\272\223\344\270\216mvc.md" "b/\344\275\225\347\264\253\346\202\246/20241213-\346\225\260\346\215\256\345\272\223\344\270\216mvc.md" new file mode 100644 index 0000000..2ba7229 --- /dev/null +++ "b/\344\275\225\347\264\253\346\202\246/20241213-\346\225\260\346\215\256\345\272\223\344\270\216mvc.md" @@ -0,0 +1,66 @@ +## 先决条件 +.NET SDK +## 创建新项目 +``` +dotnet new mvc -o Blog +cd Blog +``` +## 安装 Entity Framework Core +为目标对象的 EF Core 数据库提供程序安装程序包 + +dotnet add package Microsoft.EntityFrameworkCore.SqlServer +## 创建模型 +``` +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; + +public class BloggingContext : DbContext +{ + public DbSet Blogs { get; set; } + + + + // The following configures EF to create a Sqlite database file in the + // special "local" folder for your platform. + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + + var connectionString = $"server=.\\SQLEXPRESS;database=Blog;uid=sa;pwd=123456;TrustServerCertificate=True;"; + base.OnConfiguring(optionsBuilder); + optionsBuilder.UseSqlServer(connectionString); + } +} + +public class Blog +{ + public int BlogId { get; set; } + public string Url { get; set; } + + public List Posts { get; } = new(); +} + +public class Post +{ + public int PostId { get; set; } + public string Title { get; set; } + public string Content { get; set; } + + public int BlogId { get; set; } + public Blog Blog { get; set; } +} +``` +## 创建数据库 +### 使用迁移创建数据库 + +1. dotnet tool install --global dotnet-ef +2. dotnet add package Microsoft.EntityFrameworkCore.Design +3. dotnet ef migrations add InitialCreate +4. dotnet ef database update + +migrations 命令为迁移搭建基架,以便为模型创建一组初始表。 database update 命令创建数据库并向其应用新的迁移。 \ No newline at end of file -- Gitee