1. 程式人生 > >ASP.NET Core使用EF Core操作MySql資料庫

ASP.NET Core使用EF Core操作MySql資料庫

ASP.NET Core操作MySql資料庫, 這樣整套環境都可以佈署在Linux上

使用微軟的 Microsoft.EntityFrameworkCore(2.1.4) 和MySql出的 MySql.Data.EntityFrameworkCore(8.0.13)

 

軟體版本

Asp.net Core:2.1

MySql:5.6

 

專案結構

Snai.Mysql 是 Asp.net core 2.0 Api網站,Database 下的是MySql建庫建表指令碼

專案實現

一、MySql 建庫建表

使用 Database下的 mysql 建庫 表 主鍵 索引.sql 指令碼建庫建表,指令碼如下:

CREATE DATABASE alan CHARACTER SET utf8 COLLATE utf8_general_ci
;

USE alan
;

CREATE TABLE student(
    id INT AUTO_INCREMENT PRIMARY KEY,            -- 自增列需為主鍵
    `name` NVARCHAR(32) NOT NULL DEFAULT '',
    sex TINYINT NOT NULL DEFAULT 1,                -- 0 男生,1 女生,2 保密
    age INT NOT NULL
DEFAULT 0 ) ; ALTER TABLE student ADD INDEX ix_student_name(`name`) -- UNIQUE INDEX 唯一索引

建庫時加上 CHARACTER SET utf8 COLLATE utf8_general_ci 程式碼,設定資料庫字符集為 utf8,配合程式的資料庫連線串加上 CharSet=utf8,防止中文儲存時亂碼

如果建庫時不是utf8,就把字符集改為utf8

二、EF Core 連線操作 MySql 資料庫

1、新建專案,新增EF Core 和 MySql驅動依賴項

新建 asp.net core api 網站程式,NuGet 新增依賴項 Microsoft.EntityFrameworkCore.Tools(2.1.4) 和 MySql.Data.EntityFrameworkCore(8.0.13) 包

2、新增實體類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 Snai.Mysql.Entities
{
    [Table("student")]
    public class Student
    {
        [Column("id")]
        public int ID { get; set; }

        [Column("name")]
        public string Name { get; set; }

        [Column("sex")]
        public byte Sex { get; set; }
        
        [Column("age")]
        public int Age { get; set; }
    }
}

在根目錄下加上 DataAccess 目錄做為資料庫操作目錄,在該目錄下加上 Base 目錄做資料庫上下文目錄

在 Base 目錄下新建 AlanContext 上下文類,繼承 DbContext 類,通過建構函式注入資料庫連線,新增 DbSet<Student> 實體屬性,程式碼如下:

using Microsoft.EntityFrameworkCore;
using Snai.Mysql.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Snai.Mysql.DataAccess.Base
{
    public class AlanContext:DbContext
    {
        public AlanContext(DbContextOptions<AlanContext> options)
            : base(options)
        { }

        public DbSet<Student> Student { get; set; }
    }
}

3、添、刪、改、查 資料庫記錄

在 DataAccess 目錄下新建 Interface 目錄,用於儲存資料庫操作的介面,在該目錄下新建 IAlanDao 介面,在接口裡增加 CreateStudent(),GetStudents(),GetStudentByID(),UpdateStudent(),UpdateNameByID(),DeleteStudentByID() 資料庫 添、刪、改、查介面,程式碼如下:

using Snai.Mysql.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Snai.Mysql.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 Snai.Mysql.DataAccess.Base;
using Snai.Mysql.DataAccess.Interface;
using Snai.Mysql.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Snai.Mysql.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;
        }

        //取全部記錄
        public IEnumerable<Student> GetStudents()
        {
            return Context.Student.ToList();
        }

        //取某id記錄
        public Student GetStudentByID(int id)
        {
            return Context.Student.SingleOrDefault(s => s.ID == id);
        }

        //根據id更新整條記錄
        public bool UpdateStudent(Student student)
        {
            Context.Student.Update(student);
            return Context.SaveChanges() > 0;
        }

        //根據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 DeleteStudentByID(int id)
        {
            var student = Context.Student.SingleOrDefault(s => s.ID == id);
            Context.Student.Remove(student);
            return Context.SaveChanges() > 0;
        }
    }
}

4、新增 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 Snai.Mysql.DataAccess.Interface;
using Snai.Mysql.Entities;

namespace Snai.Mysql.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 "學生刪除失敗";
            }
        }
    }
}

5、配置資料庫連線串,註冊資料庫連線到容器,註冊資料庫操作類到容器,修改路由

在 appsettings.json 中配置資料庫連線串 "AlanConnection": "server=localhost;port=3306;database=alan;uid=root;pwd=123456;CharSet=utf8" CharSet=utf8 是為了配合資料庫 utf8 字符集,防止中文亂碼:

{
  "ConnectionStrings": {
    "AlanConnection": "server=localhost;port=3306;database=alan;uid=root;pwd=123456;CharSet=utf8"
  }
}

修改 Startup.cs 類的 ConfigureServices() 方法,註冊資料庫連線,註冊資料庫操作類

註冊資料庫連線 services.AddDbContext<AlanContext>(options => options.UseMySQL(Configuration.GetConnectionString("AlanConnection")));

UseMySql() 為使用 MySql 資料庫,如果是 Sql Server 則使用 UseSqlServer()

註冊資料庫操作類 services.AddScoped<IAlanDao, AlanDao>();

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AlanContext>(options => options.UseMySQL(Configuration.GetConnectionString("AlanConnection")));
    services.AddScoped<IAlanDao, AlanDao>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

修改路由,新增預設路由,以  controller、action,MVC的路徑方式訪問而不是 restful api 路徑方式訪問

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

到此程式碼編寫已完成

三、執行測試資料庫添、刪、改、查

執行專案

1、新增記錄,開啟 http://localhost:5000/Student/Create?name=小木&sex=0&age=18 地址,資料插入成功

image

微信截圖_20181130103801

2、查詢全部記錄,開啟 http://localhost:5000/Student/Gets 地址,取姓名列表成功

image

image

3、查詢指定id的記錄,開啟 http://localhost:5000/Student/Get?id=1 地址,取姓名成功

image

4、更新指定id的整條記錄,開啟 http://localhost:5000/Student/Update?id=1&name=小森&sex=1&age=18 地址,更新整條記錄成功

image

image

5、更新指定id的姓名,開啟 http://localhost:5000/Student/UpdateName?id=2&name=amos 地址,更新姓名成功

image

image

6、刪除指定id的記錄,開啟 http://localhost:5000/Student/Delete?id=2 地址,刪除記錄成功

image

image

 

EF Core 添、刪、改、查 MySql 資料庫已完成

原始碼訪問地址:https://github.com/Liu-Alan/Snai.Study/tree/master/Snai.Mysql