1、nuget
Pomelo.EntityFrameworkCore.MySql
2、appsettings.json
"AllowedHosts": "*", "ConnectionStrings": { "MySqlConnection": "server=localhost;port=3306;user=root;password=123456;database=wzhTest;" }
3、Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); var connectionString = Configuration.GetConnectionString("MySqlConnection"); ServerVersion serverVersion = ServerVersion.AutoDetect(connectionString); services.AddDbContext<DataContext>(options =>options.UseMySql(connectionString, serverVersion)); }
4、Models创建DataContext.cs
public class DataContext: DbContext { public DbSet<Weight> Weight { get; set; } public DbSet<Test> Test { get; set; } public DataContext(DbContextOptions<DataContext> options) : base(options) { } }
Weight和Test是数据库表类,自己创建
5、控制器中创建DataContext
public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly DataContext db; public HomeController(ILogger<HomeController> logger, DataContext dbContext) { _logger = logger; this.db = dbContext; } public IActionResult Index() { return View(); } public IActionResult getTest() { var list = db.Test.ToList<Test>(); return Json(list); }