EntityFramework 6.0< Code First > 连接 Mysql数据库
一,安装:
1、开发环境: VS2013与EF6
2、Mysql数据库为:Mysql Server 6.0
3、安装:Mysql for Visual Studio 1.1.1
下载位置:https://cdn.mysql.com/Downloads/MySQLInstaller/mysql-visualstudio-plugin-1.1.1.msi
4、安装 Mysql Connector/Net 6.8.3 GA
下载位置:http://dev.mysql.com/downloads/connector/net/
二,引用dll:
1、采用Nuget安装EF6.0.2;
2、采用Nuget安装MySql.Data.Entity.EF6
注意:要采用Nuget进行安装,否则可能会缺少相应的dll或者是配置信息
三、配置 web.config或app.config
1、将entitframework节点替代为:
<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>
2、添加 ConnectionString节点:
<connectionStrings>
<add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=数据库名称;user id=Mysql的登录用户名;password=Mysql server密码;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
四、测试C#代码
using System.Data.Entity; namespace StudyEF{ public class MyContext : DbContext{ public MyContext() : base("name=MyContext"){ } public DbSet<Data> Datas { get; set; } } public class Data{ public int Id { get; set; } public string Name { get; set; } } class Program{ static void Main(string[] args){ Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>()); var context = new MyContext(); context.Datas.Add(new Data{Name="EF6-MySql"}); context.SaveChanges(); } } }
五、在Mysql的cmd下查询: