asp.net core中使用ef core操作mysql
1.添加nuget包
Pomelo.EntityFrameworkCore.MySql
2.新增一个继承于DbContext的类,如MySqlDbContext
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; public class MySqlDbContext:DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql("server=localhost;uid=root;pwd=123456;database=mstoos20;", options => {
//设置mysql版本信息(我用的是mysql5.5) options.ServerVersion("5.5.62-log - Source distribution"); }); base.OnConfiguring(optionsBuilder); }
public DbSet<Models.LoginUser> LoginUser { get; set; } }
3.新增一个实体类LoginUser
using System.ComponentModel.DataAnnotations; namespace Models { public class LoginUser { [Key] public string code { get; set; } public string name { get; set; } public string pwd { get; set; } } }
4.在Startup.cs类中将DbContext加到ConfigureServices方法中,如下所示
public void ConfigureServices(IServiceCollection services) { //***省略其他 services.AddDbContext<Data.MySqlDbContext>(); }
5.数据库迁移(以visual studio为例,在nuget控制台管理器中输入命令)
Add-Migration initCreate
Update-Database
6.新建一个Controller名为AdminController
public class AdminController : Controller { private readonly MySqlDbContext sqlDb; public AdminController(Data.MySqlDbContext sqlDb) { this.sqlDb = sqlDb; }
[HttpPost]
public IActionResult Login(string code,string pwd)
{
var data = sqlDb.LoginUser.SingleOrDefault(a => a.code == code && a.pwd == pwd);
if (data != null)
{
this.HttpContext.Session.Set("code", Encoding.UTF8.GetBytes(data.code));
this.HttpContext.Session.Set("name", Encoding.UTF8.GetBytes(data.name));
return Json(new { code = 1, msg = "登录成功" });
}
return Json(new { code = -1, msg = "账号密码输入有误" });
}
}

浙公网安备 33010602011771号