How do I connect to the MySQL database using EF codefirst?
Environment: VS2015, Win7,. NetFramework4.5.2, MySql5.6
First, the basic operation
1, create MVC5 project: Zmsoftswebmvc.
2. Install through NuGet Package Manager: MySql.Data.EntityFramework
3. Web. config Add connection string connectionstrings
<add name="default" connectionstring="data source=.; Initial catalog=zmdb; Trusted_connection=true; "providername="System.Data.SqlClient "/>
4. Create a DbContext class
Public class Zmdbcontext:dbcontext { publicbase("default") { } Public Virtual Get Set ; } }
5. Use enable-migrations to turn on migration, automatically generate configuration files
Ii. MySQL configuration 1. Basic Configuration
A. Download MySQL for Visual Studio
https://dev.mysql.com/downloads/windows/visualstudio/
B, Installation connector
https://dev.mysql.com/downloads/connector/net/
C, modify the My.ini
Find the following information, if there is no add # in front of it, fill it up. If there is no comment, an exception occurs: Unknown storage engine ' InnoDb '
# skip-innodb#loose-skip-innodb
2. Program Configuration
A. Modify the Web. config
First, modify the connectionstrings;
Add sslmode = none; The Internet has added port= 3306;
If save Chinese garbled, need to add Character Set=utf8;
<add name="default" connectionstring="Server=localhost;database=zmdb; Uid=root; pwd=123456; Sslmode = none; "providername="MySql.Data.MySqlClient "/>
Do not add sslmode = none; An exception may occur: The provider did not return a providermanifesttoken string. ---> MySql.Data.MySqlClient.MySqlException:The host localhost does not a support SSL connections.
Then, modify the DbProviderFactories
<system.data> <DbProviderFactories> <remove invariant="MySql.Data.MySqlClient"/> <add name="MySQL Data Provider"Invariant="MySql.Data.MySqlClient"description=". Net Framework Data Provider for MySQL"type="MySql.Data.MySqlClient.MySqlClientFactory, Mysql.data, version=8.0.10.0, Culture=neutral, publickeytoken= C5687FC88969C44D"/> </DbProviderFactories></system.data>
B. Modify the ZmDbContext.cs file
[Dbconfigurationtype (typeof(mysqlefconfiguration))] Public class Zmdbcontext:dbcontext { .... }
C, modify the configuration
Public Configuration () { false; Setsqlgenerator ("MySql.Data.MySqlClient"new Mysqlmigrationsqlgenerator ()); // set SQL generator to MySQL }
Third, EF migration
1. Add a migration file
Add-migration Init
2. Migration
Update-database–verbose
Currently encountering a problem, when the initialization of seed in the configuration, insert database garbled, passing the great God help busy
Demo:https://gitee.com/zmsofts/xincunshanniandaima/blob/master/zmsoftsmp.rar
Reference article:
Https://www.cnblogs.com/kexxxfeng/p/5095812.html
Https://www.cnblogs.com/alunchen/p/7188562.html
EF6 Codefirst using MySQL