Code First介绍: Code First模式是一种很cool的模式,手动创建POCO(全称Plain Old Class Object,也就是最基本的CLR Class,实体类)类,数据层DbContext及映射关系,通过Database.SetInitializer(本次采用dbcontext.Database.CreateIfNotExists方法)生成数据库,自动生成方便快速、更易维护、非常灵活。
一、安装Entity Framework,添加引用的程序集:
添加system.data,
最终引用集效果如下:
二、新建上下文类DBcontext
public class BaseContext<TContext>
: DbContext where TContext : DbContext
{
public BaseContext(string connectName)
: base(connectName)
{
Database.SetInitializer<TContext>(null);
}
}
public class CommonContext : BaseContext<CommonContext>
{
public CommonContext(string connectName)
: base(connectName)
{
}
//public DbSet<score_records> CommonScoreRecordsTable { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new scoreRecordsConfig()); //设置主键
}
public DbSet<score_records> score_records { get; set; }
}
class scoreRecordsConfig : EntityTypeConfiguration<score_records>
{
public scoreRecordsConfig()
{
HasKey(c => c.id);
}
}
scoreRecordsConfig()函数用来定义数据实体的主键,如下图例子,数据实体声明【Key】,config函数里设置主键为id字段。
public class score_records
{
[Key]
public int id { get; set; }//成绩记录编号
public int cid { get; set; }//班级id
public int sid { get; set; }//学生id
public string sname { get; set; }//学生name
public int c_sco { get; set; }//语文score
public int m_sco { get; set; }//数学score
public int e_sco { get; set; }//英语score
public string date { get; set; } //考试日期2019-1-1格式
public int rank { get; set; } //每次考试的总分排名
}
三、 public class BaseContext,这个上下文的类名为BaseContext,所以在App.config中增加name为BaseContext的数据库连接字符串,id和password为对应的数据的id和password。
<connectionStrings>
<add name="BaseContext"
connectionString="server=127.0.0.1;User Id=isoftstone;password=isoftstone;Persist Security Info=True;database=score;Character Set =utf8"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
四、APP.config和项目目录 最终效果如下
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<connectionStrings>
<add name="BaseContext"
connectionString="server=127.0.0.1;User Id=isoftstone;password=isoftstone;Persist Security Info=True;database=score;Character Set =utf8"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
</configuration>
五、在主程序中,执行向数据库中添加数据的代码
class Program
{
static string[] lastName = new string[10] { "李", "王", "张", "刘", "陈", "杨", "赵", "黄", "周", "吴" };
static string[] firstName = new string[20] { "俊", "威", "英", "壮", "焕", "挺", "秀", "伟", "雄", "巍", "松", "柏", "石", "婵", "娟", "姣", "婷", "媚", "妩", "倩" };
static void creatScoreRecords()
{
CommonContext dbcontext = new CommonContext("BaseContext");//新建上下文类
dbcontext.Database.CreateIfNotExists();
//当对应的表不存在时,会自动创建数据库,数据库名就是connectstrings里的database,表名就是数据实体类名,各个字段对应类属性
score_records TempRecord = new score_records();
for (int i = 0; i < 5; i++) //5个班
{
TempRecord.cid = i + 1;
for (int j = 0; j < 30; j++) //每个班30人
{
TempRecord.sid = 202001 + j;//生成学生id,以2020XXXX格式
Random ran = new Random(Guid.NewGuid().GetHashCode());
string s1 = lastName[ran.Next(0, 9)]; //生成学生姓名s1+s2+s3
string s2 = firstName[ran.Next(0, 19)];
string s3 = "";
if (ran.NextDouble() > 0.5) s3 = firstName[ran.Next(0, 19)];
TempRecord.sname = s1 + s2 + s3;
for (int k = 1; k <= 6; k++) //每人6次考试
{
Date date = new Date(2019, k, 1);
TempRecord.date = date.ToString("O");
TempRecord.exemId = k;
TempRecord.c_sco = ran.Next(55, 101);
TempRecord.e_sco = ran.Next(55, 101);
TempRecord.m_sco = ran.Next(55, 101);
dbcontext.score_records.Add(TempRecord);
dbcontext.SaveChanges();
}
}
}
}
}
六、可以看到数据库中,添加了数据