标签:
CodeFirst 用中文说是代码优先,此技术可以让我们先写代码,然后由Entity Framework根据我们的代码建立数据库
接下来用学生这个例子来演示,有学生表,课程表,和成绩表三张表
首先是Model层
fee_item
public class fee_item : feemodel
{
public fee_item()
{
type = feeItemType.Normal;
}
[Required]
[StringLength(16, MinimumLength = 2)]
public string name { get; set; }//缴费类型
[Required]
[StringLength(16, MinimumLength = 8)]
public string code { get; set; }
public feeItemType type { get; set; }
public bool State { get; set; }//是否启用
}
[Key]表示在数据库中该字段为主键,[Required]表示不为空,[StringLength]也就是长度了
这一步完成之后,我们要建立一个StudentInfoEntities的类,这个类要继承自DbContext,而DbContext类在System.Data.Entity命名空间下,需引用EntityFramework.dll类库,
如安装不了,可以去Visual Studio Gallery下载,其实,只需要引用一个叫做Entity Framework的dll类库即可
FeeDbContext类
public FeeDbContext() : base("FeeDbContext") { }//base("FeeDbContext")连接数据库
public DbSet<organization> organization { get; set; }
public DbSet<org_fee> org_fee { get; set; }
public DbSet<fee_item> fee_item { get; set; }
public DbSet<item_fee_time> item_fee_time { get; set; }
public DbSet<bill_power> bill_power { get; set; }
public DbSet<bill_net> bill_net { get; set; }
public DbSet<bill_cet46> bill_cet46 { get; set; }
public DbSet<bill_insurance> bill_insurance { get; set; }
public DbSet<bill_tuition> bill_tuition { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Ignore<LookupSignType>();
}
可以加一些默认值进去
public void Initialize(FeeDbContext context)
{
List<dept> depts = new List<dept>() {
new dept(){oid=1, name="新中新集团", state=true},
new dept(){oid=2, name="山东大学", state=true},
new dept(){oid=3, name="浙江大学", state=true},
new dept(){oid=4, name="同济大学", state=true}
};
List<organization> orgs = new List<organization>() {
new organization(){oid=1, name="新中新集团", state=true},
new organization(){oid=2, name="山东大学", state=true},
new organization(){oid=3, name="浙江大学", state=true},
new organization(){oid=4, name="同济大学", state=true}
};
//depts.ForEach(o => context.dept.Add(o));
orgs.ForEach(o => context.organization.Add(o));
context.SaveChanges();
}
最后
public void Build()
{
try
{
var context = new FeeDbContext();
if (!context.Database.Exists())
{
new List<IDataInitializer<FeeDbContext>>() {
new DataInit4dept()
}.Setup<FeeDbContext>(context);
}
}
catch (Exception e)
{
Console.WriteLine("数据库初始化报错:" + e.Message);
throw e;
}
}
点击调试,触发一下,查看数据库
code first 创建数据库
标签:
原文地址:http://www.cnblogs.com/simadi/p/5401330.html