1 项目添加 Pomelo.EntityFrameworkCore.MySql
2 编辑项目文件,在节点中添加如下代码:
netcoreapp2.2
InProcess
3 CMD 切换到当前项目目录,执行如下命令
dotnet ef dbcontext scaffold "Server=localhost;User Id=数据库访问用户;Password=数据库访问密码;Database=你的数据库名" "Pomelo.EntityFrameworkCore.MySql" -o Models -f
-o 输出到目录
-f 覆盖文件
4 控制器添加数据库访问代码
控制器代码.png
ViewData["users"] = db.Users.First();
public class HomeController : Controller
{
public IActionResult Index()
{
using (var db = new boomContext())
{
ViewData["users"] = db.Users.First();
}
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
5 视图添加如下代码
视图.png
6 运行如下图
运行.png