1、新建.NetCore项目
添加依赖项
Microsoft.EntityFrameworkCore.Tools
MySql.Data.EntityFrameworkCore
2、然后新建一个DbContext类。
public class DBContext:DbContext
{
public DBContext(DbContextOptions<DBContext> options)
: base(options)
{
}
public DbSet<student> student { 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);
}
3、创建数据库映射
注意:大小写和数据库保持一致
public class student
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
4、appsettings.json里添加连接字符串
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": { "MysqlConnection": "Data Source=localhost;Database=test;User ID=root;Password=123456;pooling=true;CharSet=utf8;port=3306;sslmode=none" }
}
5、在Startup.cs文件的ConfigureServices方法添加
public void ConfigureServices(IServiceCollection services)
{
//注意:一定要加 sslmode=none
var connection = Configuration.GetConnectionString("MysqlConnection");
services.AddDbContext<DBContext>(options => options.UseMySQL(connection));
services.AddMvc();
}
6、获取集合
private readonly DBContext _db;
//通过.NET Core框架自动为我们做构造函数依赖注入IOC。
public HomeController(DBContext db)
{
_db = db;
}
public ActionResult Index()
{
var list= _db.student.ToList();
return View();
}