首先引入nutget包
第二步根目录创建一个文件夹名字自取,再建一个SqlContent类
using Microsoft.EntityFrameworkCore;
using System.Data.Entity;
using DbContext = Microsoft.EntityFrameworkCore.DbContext;
namespace YuanFuTouBao2022Core.Dao
{
public class SqlContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
string connectStr = "server=.;port=3306;database=aaa;uid=aaa;pwd=123;CharSet=utf8";
//注意了,下面的那么Version是mysql的版本号,8.0.3是我的版本号,你可以通过在cmd中输入
//mysql --help查看自己的版本号
optionsBuilder.UseMySql
(connectStr, new MySqlServerVersion(new Version(8, 0, 29)));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
}
public Microsoft.EntityFrameworkCore.DbSet<YFTB_LoginUser> YFTB_LoginUser { get; set; }
}
}
把实体类YFTB_LoginUser加上
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace YuanFuTouBao2022Core.Dao
{
[Table("YFTB_LoginUser")]
public class YFTB_LoginUser
{
[Key]
[Column("id")]
public int ID { get; set; }
[Column("name")]
public string name { get; set; }
[Column("pwd")]
public string pwd { get; set; }
}
}
ok 搞定
最后在controller中 使用即可
namespace XinHua2021.Controllers
{
public class LoginController : Controller
{
SqlContext sqlContext = new SqlContext();
public IActionResult Index()
{
var a = sqlContext.YFTB_LoginUser.ToList();
return View();
}
}
}