通过Mysql连接ASP.Net Core2.0(Code First模式)
ASP.NET Core2.0连接Mysql,首先新建项目
选择Web应用程序
选择需要身份验证:
通过Nuget安装Mysql驱动,这里推荐>Pomelo.EntityFrameworkCore.MySql(记得勾选预览版,目前只有此版本,虽然是预览,但是有rtm标识,所以放心就好)
具体使用细则,请参考:Pomelo.EntityFrameworkCore.MySql使用细则
增加Startup类中对Mysql的支持
把默认的options.UseSqlServer修改为options.UseMySql
public void ConfigureServices(IServiceCollection services) { //services.AddDbContext<ApplicationDbContext>(options => // options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));//Mysql支持 services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc() .AddRazorPagesOptions(options => { options.Conventions.AuthorizeFolder("/Account/Manage"); options.Conventions.AuthorizePage("/Account/Logout"); }); // Register no-op EmailSender used by account confirmation and password reset during development // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 services.AddSingleton<IEmailSender, EmailSender>(); }
Mysql实例信息:uid;root pwd:111111
打开appsettings.json文件,配置Mysql的连接字符串信息:
{ "ConnectionStrings": { //"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-ASP.NETCore20ToMysql-53bc9b9d-9d6a-45d4-8429-2a2761773502;Trusted_Connection=True;MultipleActiveResultSets=true", "MySqlConnection": "Server=localhost;database=ASP.NetCore-Mysql;uid=root;pwd=111111;" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } } }
运行网站,效果如下:
此时还未与数据库通信,需要触发如登录,注册等需要连接数据库的动作时,才会通过EF与数据库通信,并且发挥CodeFirst的作用,由应用程序的Model建立数据库的表结构,此处可点击Login后登录出现如下界面:
第一次运行会出现如下错误,是由于实体与数据库不统一,需要迁移所致,点击ApplyMigrations同意迁移后刷新网页即可
此时,打开Mysql数据库查看数据库是否新建成功
perfect,达到了预期效果
CodeFirst模式真是微软EF的一大利器,高效开发数据库应用必备哈
还有一种dbfirst模式:
执行以下命令创建实体:
Scaffold-DbContext "Data Source=.;Initial Catalog=Blogging;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models(Models是文件夹)
命令格式为:Scaffold-DbContext "Data Source=.;Initial Catalog=Blogging;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models