ASP.NET Core使用EF Core操做MySql數據庫

ASP.NET Core操做MySql數據庫, 這樣整套環境均可以佈署在Linux上mysql

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

 

軟件版本 github

Asp.net Core:2.1sql

MySql:5.6數據庫

 

項目結構json

Snai.Mysql 是 Asp.net core 2.0 Api網站,Database 下的是MySql建庫建表腳本api

項目實現微信

1、MySql 建庫建表restful

使用 Database下的 mysql 建庫 表 主鍵 索引.sql 腳本建庫建表,腳本以下:app

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

2、EF Core 鏈接操做 MySql 數據庫

一、新建項目,添加EF Core 和 MySql驅動依賴項

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

二、添加實體類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; }
    }
}

三、添、刪、改、查 數據庫記錄

在 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;
        }
    }
}

四、添加 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 "學生刪除失敗";
            }
        }
    }
}

五、配置數據庫鏈接串,註冊數據庫鏈接到容器,註冊數據庫操做類到容器,修改路由

在 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?}");
    });
}

到此代碼編寫已完成

3、運行測試數據庫添、刪、改、查

運行項目

一、添加記錄,打開 http://localhost:5000/Student/Create?name=小木&sex=0&age=18 地址,數據插入成功

image

微信截圖_20181130103801

二、查詢所有記錄,打開 http://localhost:5000/Student/Gets 地址,取姓名列表成功

image

image

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

image

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

image

image

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

image

image

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

image

image

 

EF Core 添、刪、改、查 MySql 數據庫已完成

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

相關文章
相關標籤/搜索