200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > ASP.NET Core Web项目连接MySQL数据库

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

时间:2019-06-30 11:16:44

相关推荐

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

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

操作步骤:

1.本地安装MySQL

参阅:MySql的配置——详细教程

我安装的是8.0.30版本的MySQL。

安装好数据库之后,新建一个MySQL连接:

注意此处的主机名为localhoust,这个很重要,在后续的数据库连接字符串中对应Data Source=localhost

新建好连接之后,新建一个名为csharp_demo的数据库,其对用数据库连接字符串中的Database=csharp_demo。然后新建一个student表,表中再添加几条数据。

2.本地新建 Core MVC项目

新建好后会有如图所示的项目目录结构:

配置 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 ponentModel.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等文件,每个文件的内容都在上文中给出。

最终运行项目:

成功从数据库中拿到数据!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。