这里并不是EF的CodeFirst模式,而是把EF配置项从配置文件,移到程序代码中了,在基于配置文件的程序中,最小化的EF配置有
注册提供程序、连接工厂、EF框架注册,如果项目作为DLL库需要提供给其它项目使用,那么在宿主项目的配置文件中,要包含EF的配置项,这是很不方便的,基于代码配置只需要引用DLL即可,无需在配置文件中配置EF项。
建表
create table student
(
id int primary key auto_increment,
name varchar(100) not null,
class varchar(100) not null,
writetime datetime not null
)
创建DLL库项目,并安装EF框架,及Mysql数据库驱动
EF配置对象,继承至DbConfiguration。
public class MyDbConfig: DbConfiguration
{
public MyDbConfig()
{
this.SetDefaultConnectionFactory(new MySql.Data.Entity.MySqlConnectionFactory());
this.SetProviderServices("MySql.Data.MySqlClient", new MySql.Data.MySqlClient.MySqlProviderServices());
}
}
数据库上下文
[DbConfigurationType(typeof(MyDbConfig))]
public class TestDbContext:DbContext
{
public TestDbContext():base("name=test")
{
}
public virtual DbSet<student> student { get; set; }
}
配置文件只需要配置数据库连接串和ADO.NET提供程序即可
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="test" connectionString="数据库连接字符串" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
<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=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
</configuration>
using (TestDbContext db = new TestDbContext())
{
db.student.ToList().ForEach(u =>
{
Console.WriteLine(u.name);
});
}