efcore连接mysql

引入包:

dotnet add package Microsoft.EntityFrameworkCore --version 3.1.10

dotnet add package mysql.data

dotnet add package mysql.data.entityframeworkcore 

创建:AbcDbContext

using Microsoft.EntityFrameworkCore;

namespace webapp.DataAccess
{
    public class AbcDbContext : DbContext
    {
        public DbSet<Aaa> aaa { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySQL(
                @"server=localhost;uid=root;pwd=123456;port=3306;database=mydb;sslmode=Preferred");
        }
    }

    public class Aaa
    {
        public int id { get; set; }
        public string Name{ get; set; }
    }

}

修改Controller:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using webapp.Models;
using webapp.DataAccess;

namespace webapp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            List<Aaa> list =new List<Aaa>();
            using (var db = new KwnDbContext())
            {
                list = db.aaa.ToList();
            }
            return View(list);
        }

    }
}

修改页面:

@{
    ViewData["Title"] = "Home Page";
}
@model List<webapp.DataAccess.Aaa>

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <h2>@Model.Count</h2>
    @foreach (var item in Model)
    {
        <label>@item.Name</label>
    }
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
原文地址:https://www.cnblogs.com/kwoon/p/14069354.html