• ASP.NET Core Web项目连接MySQL数据库


    作者在新建了一个ASP.NET Core Web项目的基础上,想连接本地的Mysql数据库,参考了很多博客,各种各样的说法都有,多少让人有感凌乱!自己最后捣鼓成功了!所以写一篇博客,以便后人查阅!

    操作步骤:

    1.本地安装MySQL

    参阅:MySql的配置——详细教程
    我安装的是8.0.30版本的MySQL。

    安装好数据库之后,新建一个MySQL连接:
    在这里插入图片描述
    注意此处的主机名为localhoust,这个很重要,在后续的数据库连接字符串中对应Data Source=localhost

    新建好连接之后,新建一个名为csharp_demo的数据库,其对用数据库连接字符串中的Database=csharp_demo。然后新建一个student表,表中再添加几条数据。
    在这里插入图片描述

    2.本地新建ASP.NET Core MVC项目

    在这里插入图片描述
    新建好后会有如图所示的项目目录结构:
    在这里插入图片描述
    配置ASP.NET Core Web项目连接MySQL数据库的过程中,重点用到:appsetting.jsonProgram.cs两个文件。其中appsetting.json文件用于配置连接字符串,Program.cs文件用于注册数据库连接服务。

    3.Mysql连接配置

    appsetting.json中添加连接字符串,添加后的appsetting.json文件内容变为:

    {
      "ConnectionStrings": {
        "MysqlConnection": "Data Source=localhost;Database=csharp_demo;User ID=root;Password=123456;pooling=true;port=3306;sslmode=none;CharSet=utf8;" 
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    其中Data Source=localhost用于指定本地localhost数据源。
    Database=csharp_demo用于指定我创建的名为csharp_demo数据库。
    User ID=root是我的数据库root用户名。
    Password=123456是我设定的本机数据库root用户密码。

    然后在Program.cs文件中注册数据库上下文服务:

    builder.Services.AddDbContext<StudentContext>(options =>
      options.UseMySql(builder.Configuration.GetConnectionString("MysqlConnection"), new MySqlServerVersion(new Version())));
    
    • 1
    • 2

    整个Program.cs文件的代码为:

    using Microsoft.EntityFrameworkCore;
    using MySQL_Connect_Demo.Data;
    using Microsoft.Extensions.DependencyInjection;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllersWithViews();
    
    //下方指定具体版本的mysql或者使用new MySqlServerVersion(new Version())都是可以的!
    //builder.Services.AddDbContext(options =>
    //options.UseMySql(builder.Configuration.GetConnectionString("MysqlConnection"), new MySqlServerVersion("8.0.30")));
    builder.Services.AddDbContext<StudentContext>(options =>
      options.UseMySql(builder.Configuration.GetConnectionString("MysqlConnection"), new MySqlServerVersion(new Version())));
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    
    • 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

    4.数据库上下文类的配置

    在工程项目的Models文件夹下新建Student类:

    using System.ComponentModel.DataAnnotations;
    namespace MySQL_Connect_Demo.Models
    {
        public class Student
        {
            [Key]
            public int Id { get; set; }
            public string Name { get; set; } = String.Empty;
            public string Age { get; set; }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在工程项目下新建Data文件夹,然后新建StudentContext.cs类:

    using Microsoft.EntityFrameworkCore;
    using MySQL_Connect_Demo.Models;
    
    namespace MySQL_Connect_Demo.Data
    {
        public class StudentContext : DbContext
        {
            public StudentContext(DbContextOptions<StudentContext> options) : base(options)
            {
            }
    
            public DbSet<Student> Students { get; set; }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Student>().ToTable("student");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    上面OnModelCreating方法中的modelBuilder.Entity().ToTable("student");用于将数据集合映射到csharp_demo数据库的student表。

    5.新建控制器类StudentController

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using MySQL_Connect_Demo.Data;
    
    namespace MySQL_Connect_Demo.Controllers
    {
        public class StudentController : Controller
        {
    
            private readonly StudentContext _context;
    
            public StudentController(StudentContext context)
            {
                _context = context;
            }
            public async Task<IActionResult> Index()
            {
                return View(await _context.Students.ToListAsync());
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    6.新建视图

    在View文件夹下新建Student文件夹,并新建Index.cshtml文件:

    @model IEnumerable<MySQL_Connect_Demo.Models.Student>
    
    @{
        ViewData["Title"] = "Index";
    }
    
    <h2>Indexh2>
    
    <p>
        <a asp-action="Create">Create Newa>
    p>
    <table class="table">
        <thead>
            <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Id)
                    th>
                    <th>
                        @Html.DisplayNameFor(model => model.Name)
                    th>
                    <th>
                        @Html.DisplayNameFor(model => model.Age)
                    th>
                <th>th>
            tr>
        thead>
        <tbody>
    @foreach (var item in Model) {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Id)
                td>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                td>
                <td>
                    @Html.DisplayFor(modelItem => item.Age)
                td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id">Edita> |
                    <a asp-action="Details" asp-route-id="@item.Id">Detailsa> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Deletea>
                td>
            tr>
    }
        tbody>
    table>
    
    • 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

    整个项目的目录结构为:
    在这里插入图片描述
    主要在Program.cdappsettings.json文件中添加了配置内容。然后新建了StudentController.csStudentContext.csStudent.csIndex.cshtml等文件,每个文件的内容都在上文中给出。

    最终运行项目:
    在这里插入图片描述
    成功从数据库中拿到数据!

  • 相关阅读:
    希望所有计算机学生都知道这些宝藏网站
    绿肥红瘦专栏数据的爬取
    服务器连接时间长了,忘记密码,解密密码
    MySQL和Navicat的安装与配置
    【HDC 2024】华为云开发者联盟驱动应用创新,赋能开发者成长
    RationalDMIS 2020 叶片检测 -快速定义叶片截面线方法
    使用Golang Web3库进行区块链开发
    计算机视觉—车道线检测
    《C++》动态内存管理
    kafka各版本消息介绍
  • 原文地址:https://blog.csdn.net/qq_44887733/article/details/126317701