Fork Me On Github
zodream 技术 .NET Core 2018-12-06

准备

NUGET 添加依赖项

MySql.Data.EntityFrameworkCore

使用

创建数据库映射

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();
}

【参考】

1.《.NetCore中EFCore for MySql

点击查看全文
0 158 0