.NetCore 使用 Mysql

Fork Me On Github

准备

NUGET 添加依赖项

c#
 
MySql.Data.EntityFrameworkCore
1

使用

创建数据库映射

c#
          
public class user
{
    public int id { get; set; }

    public string name { get; set; }

    public string email { get; set; }

    public string avatar { get; set; }
}
12345678910

新建 DbContext类

c#
             
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);
}
12345678910111213

appsettings.json里添加连接字符串

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"
    }
}
1234567891011

Startup.cs文件的ConfigureServices方法注册

c#
      
public void ConfigureServices(IServiceCollection services)
{
    var connection = Configuration.GetConnectionString("MysqlConnection");
    services.AddDbContext(options => options.UseMySQL(connection));
    services.AddMvc();
}
123456

使用

c#
           
private readonly DBContext _db;
//通过.NET Core框架自动为我们做构造函数依赖注入IOC。
public HomeController(DBContext db)
{
    _db = db;
}
public ActionResult Index()
{
    var list= _db.student.ToList();
    return View();
}
1234567891011

【参考】

1.《.NetCore中EFCore for MySql

点击查看全文
0 444 0