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

365淘房APP官网下载 2025-08-26 12:03:03 阅读: 9248

作者在新建了一个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.json、Program.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(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(options =>

//options.UseMySql(builder.Configuration.GetConnectionString("MysqlConnection"), new MySqlServerVersion("8.0.30")));

builder.Services.AddDbContext(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 options) : base(options)

{

}

public DbSet Students { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity().ToTable("student");

}

}

}

上面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 Index()

{

return View(await _context.Students.ToListAsync());

}

}

}

6.新建视图

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

@model IEnumerable

@{

ViewData["Title"] = "Index";

}

Index

Create New

@foreach (var item in Model) {

}

@Html.DisplayNameFor(model => model.Id)

@Html.DisplayNameFor(model => model.Name)

@Html.DisplayNameFor(model => model.Age)

@Html.DisplayFor(modelItem => item.Id)

@Html.DisplayFor(modelItem => item.Name)

@Html.DisplayFor(modelItem => item.Age)

Edit |

Details |

Delete

整个项目的目录结构为: 主要在Program.cd、appsettings.json文件中添加了配置内容。然后新建了StudentController.cs、StudentContext.cs、Student.cs、Index.cshtml等文件,每个文件的内容都在上文中给出。

最终运行项目: 成功从数据库中拿到数据!