一、引用框架及DLL
1、采用Nuget安装EF6.0.2;
2、采用Nuget安装MySql.Data.Entity.EF6
采用Nuget进行安装,否则可能会缺少相应的dll或者是配置信息
二、配置 web.config或app.config
在<configuration></configuration>节点中添加(或修改)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>
在<configuration></configuration>节点中添加(或修改)connectionStrings节点为:
<connectionStrings>
<add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=mysql;user id=username;password=password;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
三、代码测试
1、建表 test,建立表对应的实体:
[Table("test")]
public class test
{
public string column1 { get; set; }
public string column2 { get; set; }
}
2、重建DbContext,设置数据集属性及定义实体主键:
public class MyContext:DbContext
{
public MyContext() : base("name=MyContext") { }
public DbSet<test> Test { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<test>().HasKey(c => c.column1); ;
}
}
3、代码测试
namespace MySQLTest
{
class Program
{
static void Main(string[] args)
{
//初始化数据库
Database.SetInitializer(new CreateDatabaseIfNotExists<MyContext>());
//实体化数据库对你
var context = new MyContext();
List<test> list=(from tb in context.Test select tb).ToList();
Console.WriteLine("column1 column2");
foreach (var item in list)
{
Console.WriteLine(item.column1+" "+item.column2);
}
Console.ReadKey();
}
}
}
得到查询结果