本文轉載自https://www.cnblogs.com/alan-lin/p/9997657.html
一、新建數據表及項目
1、新建測試用表
CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `sex` bit(1) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
2、新建項目,添加EF Core 和 MySql驅動依賴項
新建.net core 2.1 webapi 網站程序,NuGet 添加依賴項 Microsoft.EntityFrameworkCore.Tools(2.1.14) 和 MySql.Data.EntityFrameworkCore(8.0.18) 包
3、添加實體類Student和數據庫上下文
添加實體類:新建 Entities 目錄,在目錄下新建 Student 實體類,在類上加 [Table("student")] 表名、屬性上加[Column("id")] 字段名等與表對應,代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace Test.Entities { [Table("student")] public class Student { [Column("id")] public int ID { get; set; } [Column("name")] public string Name { get; set; } [Column("sex")] public int Sex { get; set; } [Column("age")] public int Age { get; set; } } }
添加數據庫操作目錄 DataAccess,進入目錄,添加數據庫上下文目錄 Base,並在 Base 目錄下新建 AlanContext 上下文類,繼承 DbContext 類,通過構造函數注入數據庫連接,添加 DbSet<Student> 實體屬性,代碼如下:
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Test.Entities; namespace Test.DataAccess.Base { public class AlanContext : DbContext { public AlanContext(DbContextOptions<AlanContext> options) : base(options) { } public DbSet<Student> Student { get; set; } } }
4、增、刪、改、查等數據庫操作
在 DataAccess 目錄下新建 Interface 目錄,用於保存數據庫操作的接口,在該目錄下新建 IAlanDao 接口,在接口里增加 CreateStudent(),GetStudents(),GetStudentByID(),UpdateStudent(),UpdateNameByID(),DeleteStudentByID() 數據庫 添、刪、改、查接口,代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Test.Entities; namespace Test.DataAccess.Interface { public interface IAlanDao { //插入數據 bool CreateStudent(Student student); //取全部記錄 IEnumerable<Student> GetStudents(); //取某id記錄 Student GetStudentByID(int id); //根據id更新整條記錄 bool UpdateStudent(Student student); //根據id更新名稱 bool UpdateNameByID(int id, string name); //根據id刪掉記錄 bool DeleteStudentByID(int id); } }
在 DataAccess 目錄下新建 Implement 目錄,用於保存數據庫操作接口的實現,在該目錄下新建 AlanDao 類,繼承 IAlanDao 接口,實現接口里的數據庫操作方法,在構造函數注入 AlanContext 數據庫上下文,代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Test.DataAccess.Base; using Test.DataAccess.Interface; using Test.Entities; namespace Test.DataAccess.Implement { public class AlanDao : IAlanDao { public AlanContext Context; public AlanDao(AlanContext context) { Context = context; } //插入數據 public bool CreateStudent(Student student) { Context.Student.Add(student); return Context.SaveChanges() > 0; } //取某id記錄 public Student GetStudentByID(int id) { return Context.Student.SingleOrDefault(s => s.ID == id); } //取全部記錄 public IEnumerable<Student> GetStudents() { return Context.Student.ToList(); } //根據id更新名稱 public bool UpdateNameByID(int id, string name) { var state = false; var student = Context.Student.SingleOrDefault(s => s.ID == id); if (student != null) { student.Name = name; state = Context.SaveChanges() > 0; } return state; } //根據id更新整條記錄 public bool UpdateStudent(Student student) { Context.Student.Update(student); return Context.SaveChanges() > 0; } //根據id刪掉記錄 public bool DeleteStudentByID(int id) { var student = Context.Student.SingleOrDefault(s => s.ID == id); Context.Student.Remove(student); return Context.SaveChanges() > 0; } } }
5、添加 StudentController 控制器,調用數據庫操作方法
在 Controllers 目錄下,添加 StudentController 控制器,在構造函數注入 AlanDao 數據庫操作,在控制器里 創建 Create(),Gets(),Get(),Update(),UpdateName(),Delete()等方法,調用 AlanDao 數據庫操作方法,代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Test.DataAccess.Interface; using Test.Entities; namespace Test.Controllers { public class StudentController : ControllerBase { private IAlanDao AlanDao; public StudentController(IAlanDao alanDao) { AlanDao = alanDao; } //插入數據 public ActionResult<string> Create(string name, byte sex, int age) { if (string.IsNullOrEmpty(name.Trim())) { return "姓名不能為空"; } if (sex < 0 || sex > 2) { return "性別數據有誤"; } if (age <= 0) { return "年齡數據有誤"; } var student = new Student() { Name = name, Sex = sex, Age = age }; var result = AlanDao.CreateStudent(student); if (result) { return "學生插入成功"; } else { return "學生插入失敗"; } } //取全部記錄 public ActionResult<string> Gets() { var names = "沒有數據"; var students = AlanDao.GetStudents(); if (students != null) { names = ""; foreach (var s in students) { names += $"{s.Name} \r\n"; } } return names; } //取某id記錄 public ActionResult<string> Get(int id) { var name = "沒有數據"; var student = AlanDao.GetStudentByID(id); if (student != null) { name = student.Name; } return name; } //根據id更新整條記錄 public ActionResult<string> Update(int id, string name, byte sex, int age) { if (id <= 0) { return "id 不能小於0"; } if (string.IsNullOrEmpty(name.Trim())) { return "姓名不能為空"; } if (sex < 0 || sex > 2) { return "性別數據有誤"; } if (age <= 0) { return "年齡數據有誤"; } var student = new Student() { ID = id, Name = name, Sex = sex, Age = age }; var result = AlanDao.UpdateStudent(student); if (result) { return "學生更新成功"; } else { return "學生更新失敗"; } } //根據id更新名稱 public ActionResult<string> UpdateName(int id, string name) { if (id <= 0) { return "id 不能小於0"; } if (string.IsNullOrEmpty(name.Trim())) { return "姓名不能為空"; } var result = AlanDao.UpdateNameByID(id, name); if (result) { return "學生更新成功"; } else { return "學生更新失敗"; } } //根據id刪掉記錄 public ActionResult<string> Delete(int id) { if (id <= 0) { return "id 不能小於0!"; } var result = AlanDao.DeleteStudentByID(id); if (result) { return "學生刪除成功"; } else { return "學生刪除失敗"; } } } }
6、配置數據庫連接字符串,注冊數據庫連接到容器,注冊數據庫操作類到容器
在 appsettings.json 中配置數據庫連接串
{ "ConnectionStrings": { "DefaultConnection": "server=localhost;port=3306;database=alan;uid=root;pwd=123456;", } }
修改 Startup.cs 類的 ConfigureServices() 方法,注冊數據庫連接及數據庫操作類
var conn = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<AlanContext>(options => options.UseMySQL(conn)); services.AddScoped<IAlanDao, AlanDao>();
二、運行測試
運行項目
在瀏覽器中分別執行
新增:http://localhost:5000/Student/Create?name=小木&sex=0&age=18
查詢所有:http://localhost:5000/Student/Gets
指定查詢:http://localhost:5000/Student/Get?id=1
更新:http://localhost:5000/Student/Update?id=1&name=小森&sex=1&age=18
更新指定信息:http://localhost:5000/Student/UpdateName?id=2&name=amos
刪除指定信息:http://localhost:5000/Student/Delete?id=2