code first 创建数据库
CodeFirst 用中文说是代码优先,此技术可以让我们先写代码,然后由Entity Framework根据我们的代码建立数据库
接下来用学生这个例子来演示,有学生表,课程表,和成绩表三张表
首先是Model层
fee_item
{
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 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(); }
最后
{
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;
}
}
点击调试,触发一下,查看数据库
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2014-04-17 Android手机 Fildder真机抓包