如何使用EF CodeFirst連接MySql數據庫?
環境:VS2015、Win7、.NetFramework4.5.2、MySql5.6
一、基本操作
1、創建MVC5項目:ZmsoftsWebMvc。
2、通過NuGet包管理器安裝:MySql.Data.EntityFramework
3. web.config添加連接字符串connectionStrings
<add name="default" connectionString="data source=.;initial catalog=zmdb;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
4.創建一個dbcontext類
public class ZmDbContext : DbContext { public ZmDbContext() : base("default") { } public virtual DbSet<User> Users { get; set; } }
5.使用Enable-Migrations 開啟遷移,自動生成配置文件
二、MYSQL配置
1.基礎配置
A、下載MySQL for Visual Studio
https://dev.mysql.com/downloads/windows/visualstudio/
B、安裝connector
https://dev.mysql.com/downloads/connector/net/
C、修改my.ini
找到以下信息,前面如果沒有加#,就補上。如果沒有注釋,會出現異常:Unknown storage engine 'InnoDb'
# skip-innodb
#loose-skip-innodb
2.程序配置
A、修改web.config
首先,修改connectionStrings;
添加SslMode = none;,網上有的還加了port=3306;
如果保存中文出現亂碼,需要添加 Character Set=utf8;
<add name="default" connectionString="Server=localhost;Database=zmdb;Uid=root;Pwd=123456;SslMode = none;" providerName="MySql.Data.MySqlClient" />
不添加SslMode = none;可能會出現異常:The provider did not return a ProviderManifestToken string. ---> MySql.Data.MySqlClient.MySqlException: The host localhost does not support SSL connections.
然后,修改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、修改ZmDbContext.cs文件
[DbConfigurationType(typeof(MySqlEFConfiguration))] public class ZmDbContext : DbContext { .... }
C、修改Configuration
public Configuration() { AutomaticMigrationsEnabled = false; SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator());//設置Sql生成器為Mysql的 }
三、EF遷移
1.添加遷移文件
Add-Migration Init
2.遷移
Update-DataBase –verbose
目前遇到一個問題,在Configuration中Seed的初始化時,插入數據庫亂碼,路過的大神幫下忙
demo下載地址:https://gitee.com/zmsofts/XinCunShanNianDaiMa/blob/master/ZmsoftsMP.rar
參考文章:
https://www.cnblogs.com/kexxxfeng/p/5095812.html
https://www.cnblogs.com/alunchen/p/7188562.html
