标签:5.6 variant system mysql数据库 automatic framework cli known context
如何使用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 开启迁移,自动生成配置文件
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
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的 }
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
标签:5.6 variant system mysql数据库 automatic framework cli known context
原文地址:https://www.cnblogs.com/xcsn/p/9314563.html