环境:vs2013+mysql5.6+mysql connector for .net 6.8.3+MySQL for Visual Studio 1.1.3
参考:http://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html
mvc4连接mysql的资料很少,百度了一圈也没找到。一开始用的vs2013怎么也连接不上mysql,连ado.net不显示,用mysql.data的直接连接倒是能成功,但是到mvc的时候就需要各种配置了。
最后在mysql的官网上找到了资料:
1.首先要先安装MySQL for Visual Studio ,你可能会说我安装了啊,怎么还是不显示呢看官网说的:
所以你需要安装1.1版本以上的才可以,除此之外,mysql官网还说了:
Visual Studio 2013 (Professional edition and up only) is supported by MySQL Connector/Net 6.8 and up with the MySQL for Visual Studio product.
必须是vs2013 professional版本以上才可以!!
等等,mysql的官网还有条:
Always install the MySQL for Visual Studio before installing MySQL Connector/Net.
安装MySQL Connector/Net之前要先安装MySQL for Visual Studio,不知道聪明的你是不是安装反了
安装MySQL Connector/Net,可以通过NuGet工具获得,比较轻松愉快,当然你也可以自己下载,自己引用
2.
配置环境:
修改web.config
<connectionStrings> <add name="MyContext" providerName="MySql.Data.MySqlClient" connectionString="server=localhost; port=3306;database=mycontext;uid=root;password=********"/> </connectionStrings> <entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6"> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" /> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework>
添加mysql.data,mysql.data.entity.EF6到引用
下面mysql官方还温馨的建议了:
(1)在context class顶部添加:[DbConfigurationType(typeof(MySqlEFConfiguration))]
(2)添加 codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6" 到<entityFramework> 上面的字节里我已经添加了
实例代码:
[DbConfigurationType(typeof(MySqlEFConfiguration))] class JourneyContext : DbContext { public DbSet<MyPlace> MyPlaces { get; set; } public JourneyContext() : base() { } public JourneyContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } } using (MySqlConnection conn = new MySqlConnection("<connectionString>")) { conn.Open(); ... using (var context = new JourneyContext(conn, false)) { ... } }
mysql官网有一个例子,参考引用中就是,如果你设了密码会给有InnerException = {"Authentication to host ‘localhost‘ for user ‘root‘ using method ‘mysql_native_password‘ failed with message: Access denied for user ‘root‘@‘localhost‘ (using password: NO)"}" 的提示,你需要在连接字符串中增加
Persist Security Info=True;
我实现的效果:
刚开始学习mvc,感觉比webform好用一些,要是连上了过来道个喜吧