ASP.NET 初次连接数据库Mysql及初始化操作

首先按照MVC模式:

  • 在Model新建Table.cs,对应数据库的Table表;
  • 在View新建Table文件夹新建Index页面;
  • 在Controller控制器新建针对Table的TableController;

安装一些常用的扩展包

1
2
3
4
5
6
7
8
9
10
11
12
13
Id                                  Versions                                 ProjectName                                                                                                                                                         
-- -------- -----------
Microsoft.AspNetCore.Diagnostics {2.2.0} RmWebApp
Microsoft.AspNetCore.Mvc.Razor.R... {5.0.9} RmWebApp
Microsoft.EntityFrameworkCore.Sq... {5.0.9} RmWebApp
Newtonsoft.Json {13.0.1} RmWebApp
Microsoft.AspNetCore.Identity.En... {5.0.9} RmWebApp
Microsoft.VisualStudio.Web.CodeG... {5.0.2} RmWebApp
Microsoft.EntityFrameworkCore.Tools {5.0.9} RmWebApp
MySql.Data {8.0.26} RmWebApp
Pomelo.EntityFrameworkCore.MySql {5.0.1} RmWebApp
Microsoft.VisualStudio.Web.CodeG... {5.0.2} RmWebApp
Microsoft.AspNetCore.Identity.UI {5.0.9} RmWebApp

在Models中编辑Table.cs,定义Table这个表的字段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace RmWebApp.Models
{
public class Table
{
//主键
[Key]
public int Fid { get; set; }
//表名
public String TableName { get; set; }
//注释
public String Caption { get; set; }
}
}

在models中新建ApplicationDbContext.cs文件,编写上下文,继承自DbContext

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using RmWebApp.Models;

namespace RmWebApp.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Meta> Meta { get; set; }
public DbSet<Table> Table { get; set; }
}
}

在根目录新建web.config配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<configuration>

<!-- To customize the asp.net core module uncomment and edit the following section.
For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
<!--
<system.webServer>
<handlers>
<remove name="aspNetCore"/>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
-->
<connectionStrings>
<add name="ApplicationDbContext" connectionString="Data Source=localhost;port=3306; Initial Catalog=rmscada;uid=root; pwd=root" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>

说明:“ApplicationDbContext”是上下文名称,rmscada数据库名称,pwd是密码,酌情修改

修改Startup.cs启动文件,编辑 ConfigureServices部分

1
2
3
4
5
6
7
8
9
10
11
12
13
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(options
=>options.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
ServerVersion.AutoDetect(Configuration.GetConnectionString("DefaultConnection"))));

services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages().AddRazorRuntimeCompilation();

}

修改appsettings.json数据库连接文件

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=数据库名称;user=root;password=数据库密码"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

打开工具-NuGet包管理器-程序包管理控制台

初次新建的VisualStudio工程需要先输入命令

1
add-migration   

提示输入名字,这个跟工程名字不同,测试随便输入

然后输入

1
enable-migrations   

这时候项目会自动生成Migrations文件夹

最后执行

1
update-database   

该条命令执行后,Mysql数据库就会自动生成对应Models文件夹中Table.cs中定义的字段