1.创建1个web项目
2.加入Microsoft.EntityFrameworkCore依赖
3.创建数据库表
CREATE TABLE `Person` ( `id` int(11) NOT NULL AUTO_INCREMENT, `Name` varchar(20) DEFAULT NULL, `Age` int(2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
4.创建1个实体类
namespace mysql1.model
{
public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
5.创建mysql配置类
using Microsoft.EntityFrameworkCore;
using mysql1.model;
namespace mysql1.config
{
public class DBContextHelper : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql("server=xxx;port=xxx;user=xxx;password=xxx;database=xxx", new MySqlServerVersion(new Version(5, 7, 16)));
}
public virtual DbSet? Person { get; set; }
}
}
6.创建1个controller
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using mysql1.config;
using mysql1.model;
namespace mysql1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
[HttpGet(Name = "my")]
public Object Get()
{
DBContextHelper helper = new();
return helper.Database.ExecuteSqlRaw("update Person set name='拉拉' where id=29");
}
}
}



