连接方式和2.0类似,但感觉更简便了一些
首先下载驱动, nuget
需要在 startup.cs上添加如下两行代码 :
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<DatabaseContext>(options =>
options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
分别代表连接 MySQL和启用MVC模式,上面DatabaseContext,是新建的Context类,代码如下:
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public DbSet<News> News { get; set; }
}
以上基本可以测试连接数据库了