ASP.Net Core中简单使用MySQL

从新建项目后到简单显示出数据

起步

准备mysql数据表(表名User)
随意插入几个数据

在这里插入图片描述
mysql中数据表

1.NuGet加入

在这里插入图片描述
两个包倒要最新的哦
两个包直接搜索安装最新版本。必须都是最新的。否则报错

2.新建一个模板类

在这里插入图片描述
类名最好和表名相同
在这里插入图片描述
红色配置指定模板对应的表名
黄色表示成员对应的列名(同正常查询一样不区分大小写)

3.新建Data文件夹用来管理链接数据库

在这里插入图片描述
这里有三个文件分别是数据库操作接口、数据库上下文、数据库操作实现

首先新建一个数据库上下文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TimeCtrl.Models;

namespace TimeCtrl.Data
{
    public class TestContext:DbContext
    {

        public TestContext(DbContextOptions<TestContext> options)
            :base(options)
        {

        }

        public DbSet<User> User { get; set; }//DbSet<User>中user换成目标模板类,后面成员名随便写,最好都相同,比较好记
    }
}

接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TimeCtrl.Models;

namespace TimeCtrl.Data
{
    public interface ITestDao
    {
        //插入数据
        bool CreateUser(User user);

        //取全部记录
        IEnumerable<User> GetUsers();

        //取某id记录
        User GetUserByID(int id);

        //根据id更新整条记录
        bool UpdateUser(User user);

        //根据id更新名称
        bool UpdateUserNameByID(int id, string name);

        //根据id删掉记录
        bool DeleteUserByID(int id);
    }
}

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TimeCtrl.Models;

namespace TimeCtrl.Data
{
    public class TestDao:ITestDao
    {
        public TestContext testContext;//数据库操作上下文

        public TestDao(TestContext tc)//初始化
        {
            testContext = tc;
        }

        //创建
        bool ITestDao.CreateUser(User user)//传入user
        {
            /*
            //数据验证
            。。。
            */
            testContext.User.Add(user);//添加
            return testContext.SaveChanges()>0;//返回影响的行数,就是是否成功
        }

        bool ITestDao.DeleteUserByID(int id)//根据id删除
        {
            var user = testContext.User.SingleOrDefault(s => s.ID == id);//获取一个user对象,条件为id等于传入的id,
            testContext.Remove(user);//删除
            return testContext.SaveChanges() > 0;//返回影响的行数表示是否成功
        }

       
        User ITestDao.GetUserByID(int id)//根据id获取
        {
            return testContext.User.SingleOrDefault(s => s.ID == id);//返回一个匹配对象或者默认,条件是 传入id和目标ID相等
        }

        IEnumerable<User> ITestDao.GetUsers()//获取
        {
            return testContext.User.ToList();
        }

        //根据id更新名字
        bool ITestDao.UpdateUserNameByID(int id, string name)
        {
            /*
            //数据验证
            。。。
            */
            var user= testContext.User.SingleOrDefault(u => u.ID == id);//获取对象
            if (user == null)//没有获取到返回false
                return false;
            user.Name = name;//设置对象的名
            testContext.User.Update(user);//更新对象
            return testContext.SaveChanges()>0;//返回影响行数
        }

        //更新User
        bool ITestDao.UpdateUser(User user)
        {
            /*
            //数据验证
            。。。
            */
            testContext.User.Update(user);//更新user
            return testContext.SaveChanges() > 0;//返回被改变的行数
        }
    }
}

4.配置

打开appsetting.json
在这里插入图片描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "链接名": "server=localhost;port=3306;database=表名;uid=用户名;pwd=密码;CharSet=utf8"
  }
}

  }

打开startup.cs,找到ConfigureServices方法
在这里插入图片描述

1
2
3
4
5
6
7
8
public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            //添加
            services.AddDbContext<TestContext>(options => options.UseMySQL(Configuration.GetConnectionString("链接名")));
            services.AddScoped<ITestDao, TestDao>();
        }

添加或更改以下两句,用来注册链接

1
2
services.AddDbContext<TestContext>(options => options.UseMySQL(Configuration.GetConnectionString("链接名")));
services.AddScoped<ITestDao, TestDao>();

5.Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
namespace TimeCtrl.Controllers
{
    public class CsController : Controller
    {

        public ITestDao testDao;

        public CsController(ITestDao testDao)
        {
            this.testDao = testDao;
        }

        public IActionResult Index()//首页
        {
           
            return View(testDao.GetUsers());//model放入所有查询到的数据
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]//标记验证
        public IActionResult Create([Bind("Name","Password")] User user)//绑定数据
        {
            //尝试创建
            if(testDao.CreateUser(user))
            {
                //成功回到主页
                return RedirectToAction("Index", "Cs");
            }
            //失败填回数据再返回
            return View(user);
        }

        //编辑指定 id 数据
        public IActionResult Edit(int? id)
        {
            //传入id为空 回到主页
            if (id == null)
                return RedirectToAction("Index", "Cs");
            //获取指定id 传入页面显示出来
            var temp=testDao.GetUserByID((int)id);
            return View(temp);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit([Bind("ID","Name", "Password")] User user)
        {
            //更新数据
            if (testDao.UpdateUser(user))
            {
                return RedirectToAction("Index", "Cs");
            }
            return View(user);
        }
    }
}

https://localhost:port/Cs
在这里插入图片描述
点击编辑
在这里插入图片描述

在这里插入图片描述