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": "*"
}

其中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())));

整个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<StudentContext>(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();

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

在工程项目下新建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");
        }
    }
}

上面OnModelCreating方法中的modelBuilder.Entity<Student>().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());
        }
    }
}

6.新建视图

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

@model IEnumerable<MySQL_Connect_Demo.Models.Student>

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</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">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

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

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

  • 10
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值