From bf29b98c1cbf8e1222584587c9ad1ef72de9b9d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E6=A2=A6=E6=B6=B5?= <3234558314@qq.com> Date: Mon, 23 Dec 2024 08:11:39 +0800 Subject: [PATCH] 1218 --- ...45\346\225\260\346\215\256\345\272\223.md" | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git "a/\351\231\210\346\242\246\346\266\265/20241218\350\277\236\346\216\245\346\225\260\346\215\256\345\272\223.md" "b/\351\231\210\346\242\246\346\266\265/20241218\350\277\236\346\216\245\346\225\260\346\215\256\345\272\223.md" index e69de29..d10bc12 100644 --- "a/\351\231\210\346\242\246\346\266\265/20241218\350\277\236\346\216\245\346\225\260\346\215\256\345\272\223.md" +++ "b/\351\231\210\346\242\246\346\266\265/20241218\350\277\236\346\216\245\346\225\260\346\215\256\345\272\223.md" @@ -0,0 +1,130 @@ +## 连接实际数据库 +1. 一个构造函数 +```js + privite readonly 模型连接名 变量名; + public 控制器名(){ + _db = new 模型连接名(); + } +``` + +### 必要条件(一些安装命令) +1. 下载安装包:dotnet add package Microsoft.EntityFrameworkCore.SqlServer +2. 下载安装包:dotnet add package Microsoft.EntityFrameworkCore.Design +3. 下载ef工具:dotnet tool install --global dotnet-ef +4. 生成迁移文件:dotnet ef migrations add Info +5. 将迁移文件更新到数据库:dotnet ef database update + +### 代码练习 +2. 在控制器中的代码(返回的是最简单的视图) + +```cs +using Microsoft.AspNetCore.Mvc; +using StuInfo.Models; + +namespace StuInfo.Controllers; + +public class StudentsController:Controller +{ + private readonly StuContext _db; + public StudentsController(){ + _db=new StuContext(); + } + // 查询 + public IActionResult Index(int id) + { + var res=_db.Students.FirstOrDefault(x=>x.Id ==id); + return View(res); + } + public IActionResult Create(int id) + { + var res=_db.Students.FirstOrDefault(x=>x.Id ==id); + return View(res); + } + public IActionResult Edit(int id) + { + var res=_db.Students.FirstOrDefault(x=>x.Id ==id); + return View(res); + } + public IActionResult Delete(int id) + { + var res=_db.Students.FirstOrDefault(x=>x.Id == id); + return View(res); + } +} +``` +3. 数据表中的数据 +```js +namespace StuInfo.Models; + +// 学生信息表 +public class Student +{ + // 主键id + public int Id{get;set;} + // 学号 + public string StuCore{get;set;}=null!; + // 学生姓名 + public string StuName{get;set;}=null!; +} +``` +4. 连接、创建数据库代码 +```cs +namespace StuInfo.Models; + +using Microsoft.EntityFrameworkCore; + +public class StuContext : DbContext +{ + public DbSet Students {get;set;}=null!; + public DbSet Teachers{get;set;}=null!; + + // 调用OnConfiguring方法 + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); + + var connectionString=$"server=.\\SQLEXPRESS;database=MyStuDb;uid=sa;pwd=123456;TrustServerCertificate=true;"; + + optionsBuilder.UseSqlServer(connectionString); + } +} +``` +5. 视图内的代码 +```html + +@model List; + +@* 查询 *@ +
+
+ + +
+
+
+ 新增 +
+ + + + + + + + + @foreach (var item in Model) + { + + + + + + + } + + +
ID学生学号学生姓名操作
@item.Id@item.StuCore@item.StuName + 修改 + 删除 +
+``` \ No newline at end of file -- Gitee