准备
NUGET 添加依赖项
使用
创建数据库映射
public class user
{
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string avatar { get; set; }
}
新建 DbContext类
public class DBContext : DbContext
{
public DBContext(DbContextOptions options)
: base(options)
{
}
public DbSet user { get; set; }
//string str = @"Data Source=;Database=;User ID=;Password=;pooling=true;CharSet=utf8;port=3306;sslmode=none";
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =>
// optionsBuilder.UseMySQL(str);
}
appsettings.json里添加连接字符串
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MysqlConnection": "Data Source=localhost;Database=zodream;User ID=root;Password=root;pooling=true;CharSet=utf8;port=3306;sslmode=none"
}
}
Startup.cs文件的ConfigureServices方法注册
public void ConfigureServices(IServiceCollection services)
{
var connection = Configuration.GetConnectionString("MysqlConnection");
services.AddDbContext(options => options.UseMySQL(connection));
services.AddMvc();
}
使用
private readonly DBContext _db;
//通过.NET Core框架自动为我们做构造函数依赖注入IOC。
public HomeController(DBContext db)
{
_db = db;
}
public ActionResult Index()
{
var list= _db.student.ToList();
return View();
}
【参考】
转载请保留原文链接: https://zodream.cn/blog/id/20.html