1.创建项目
2.添加依赖项
3.添加数据库字符串
在appsetting.json中添加数据库信息
"DefaultDbConnect": "server=localhost;database=demo;user=root;password=123456"
数据库名称为demo,创建一个user表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `demo`.`user`(`username`) VALUES ('rookie')
4.
在Model中创建一个ApplicationDbContext.cs和User.cs
using Microsoft.EntityFrameworkCore;
namespace ConnectMySQLDemo.Models
{
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<User> user{ get; set; }
}
}
namespace ConnectMySQLDemo.Models
{
public class User
{
public int Id { get; set; }
public string username { get; set; }
}
}
5.在Startup中配置mysql
// Mysql
IConfigurationSection configurationSection = Configuration.GetSection("DefaultDbConnect");
services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(configurationSection.Value));
6.在Controller中测试
在HomeController中查询,然后在index.cshtml中显示
HomeController.cs代码如下
private ApplicationDbContext _db;
public HomeController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
var item = _db.user.FirstOrDefault(u => u.Id == 1);
return View(item);
}
index.html代码如下
@model User
@{
ViewData["Title"] = "Home Page";
}
<h1>@Model.Id</h1>
<div>@Model.username</div>
7.运行
完成