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() > ;
} //取全部记录
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() > ;
} //根据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() > ;
} return state;
} //根据id删掉记录
public bool DeleteStudentByID(int id)
{
var student = Context.Student.SingleOrDefault(s => s.ID == id);
Context.Student.Remove(student);
return Context.SaveChanges() > ;
}
}
}
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 < || sex > )
{
return "性别数据有误";
} if (age <= )
{
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 <= )
{
return "id 不能小于0";
} if (string.IsNullOrEmpty(name.Trim()))
{
return "姓名不能为空";
} if (sex < || sex > )
{
return "性别数据有误";
} if (age <= )
{
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 <= )
{
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 <= )
{
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 地址,数据插入成功
2、查询全部记录,打开 http://localhost:5000/Student/Gets 地址,取姓名列表成功
3、查询指定id的记录,打开 http://localhost:5000/Student/Get?id=1 地址,取姓名成功
4、更新指定id的整条记录,打开 http://localhost:5000/Student/Update?id=1&name=小森&sex=1&age=18 地址,更新整条记录成功
5、更新指定id的姓名,打开 http://localhost:5000/Student/UpdateName?id=2&name=amos 地址,更新姓名成功
6、删除指定id的记录,打开 http://localhost:5000/Student/Delete?id=2 地址,删除记录成功
EF Core 添、删、改、查 MySql 数据库已完成
Github源码地址:https://github.com/Liu-Alan/Snai.Study/tree/master/Snai.Mysql
ASP.NET Core使用EF Core操作MySql数据库的更多相关文章
- 以EF形式操作mysql数据库
1.引入Nuget包: 2.书写EF操作上下文 public class MySqlContext:DbContext { protected override void OnConfiguring( ...
- 在.net core web 项目中操作MySql数据库(非ORM框架,原生sql语句方式)
本案例通过MySql.Data和Dapper包执行原生sql,实现对数据库的操作. 操作步骤: 第1步:在MySql数据库中新建表User(使用Navicat For MySql工具) 建表语句: c ...
- .NET Core Dapper操作mysql数据库
前言 现在ORM盛行,市面上已经出现了N款不同的ORM套餐了.今天,我们不谈EF,也不聊神马黑马,就说说 Dapper.如何在.NET Core中使用Dapper操作Mysql数据库呢,让我们跟随镜头 ...
- net Core 通过 Ef Core 访问、管理Mysql
net Core 通过 Ef Core 访问.管理Mysql 本文地址:http://www.cnblogs.com/likeli/p/5910524.html 环境 dotnet Core版本:1. ...
- 【ASP.NET Core】EF Core - “影子属性” 深入浅出经典面试题:从浏览器中输入URL到页面加载发生了什么 - Part 1
[ASP.NET Core]EF Core - “影子属性” 有朋友说老周近来博客更新较慢,确实有些慢,因为有些 bug 要研究,另外就是老周把部分内容转到直播上面,所以写博客的内容减少了一点. ...
- .NET 5/.NET Core使用EF Core 5连接MySQL数据库写入/读取数据示例教程
本文首发于<.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据示例教程> 前言 在.NET Core/. ...
- .net core使用orm操作mysql数据库
Mysql数据库由于其体积小.速度快.总体拥有成本低,尤其是开放源码这一特点,许多中小型网站为了降低网站总体拥有成本而选择了MySQL作为网站数据库.MySQL是一个多用户.多线程的关系型数据库管理系 ...
- 一个官翻教程集合:ASP.NET Core 和 EF Core 系列教程
通过一个大学课程案例讲解了复杂实体的创建过程及讲解 1.ASP.NET Core 和 Entity Framework Core 系列教程——入门 (1 / 10) 2.ASP.NET Core 和 ...
- ASP.NET CORE 使用 EF CORE访问数据库
asp.net core通过ef core来访问数据库,这里用的是代码优先,通过迁移来同步数据库与模型. 环境:vs2017,win10,asp.net core 2.1 一.从建立asp.net c ...
随机推荐
- 97. Interleaving String (String; DP)
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given:s1 = ...
- 可重入函数reentrant function
可重入函数主要用于多任务环境中,一个可重入的函数简单来说就是可以被中断的函数:而不可重入的函数由于使用了一些系统资源,比如全局变量区,中断向量表等,所以它如果被中断的话,可能会出现问题,这类函数是不能 ...
- 基于AspectJ的XML方式进行AOP开发
-------------------siwuxie095 基于 AspectJ 的 XML 方式进行 AOP 开发 1 ...
- linux 下 php 安装 libevent
一.安装libevent库 1.到libevent官网下载安装源码 http://libevent.org/ 如:libevent-2.0.22-stable.tar.gz 2.解压源码包 > ...
- db2 快照 SNAPSHOT
打开和关闭快照缺省情况不打开 DB2 监控,必须在连接或实例级别上进行设置.有一系列监视器开关来决定是否监控某种数据元素.还预留了一个内存堆,用于包含为监控而存储的信息.1:在instance级别上设 ...
- [BAT]批处理脚本双击可运行,但在定时计划任务中无法执行(当前工作路径不对导致的)
一开始,红色部分我是用set AutoPath=%cd%,双击可执行,但是将这个批处理脚本放在定时任务中无法执行,后来发现在定时执行的时候,当前工作路径不是批处理脚本所在的路径,而是C:/Window ...
- 写点C++ 学习记录 充数
#include "stdafx.h" #include <cstdlib> #include <iostream> using namespace std ...
- Java代码实现依赖注入
http://zhangjunhd.blog.51cto.com/113473/126545 这里将模仿Spring实现一种基于xml配置文件的依赖注入机制.文件中将实现3中注入,一是单值注入,包括i ...
- Android系统root破解原理分析
http://dengzhangtao.iteye.com/blog/1543494 root破解过程的终极目标是替换掉系统中的su程序.但是要想替换掉系统中su程序本身就是需要root权限的,怎样在 ...
- 2018.10.14 loj#6011. 「网络流 24 题」运输问题(费用流)
传送门 费用流入门题. 直接按照题意模拟. 把货物的数量当做容量建边. 然后跑一次最小费用流和最大费用流就行了. 代码: #include<bits/stdc++.h> #define N ...