时间:2021-07-01 10:21:17 帮助过:3人阅读
public void Initialize(FeeDbContext context) { List<fee_item> fim = new List<fee_item>() { new fee_item(){name="电费",code="pow",type= feeItemType.Normal,State=true,Icon="img/jf_dianf.png",sort=0,appid=0,reg_time=DateTime.Now}, new fee_item(){name="网费",code="net",type= feeItemType.Normal,State=true,Icon="img/jf_wangf.png",sort=1,appid=1,reg_time=DateTime.Now}, new fee_item(){name="四六级",code="cet",type= feeItemType.Normal,State=true,Icon="img/jf_siliuj.png",sort=2,appid=2,reg_time=DateTime.Now}, new fee_item(){name="报名费",code="pow",type= feeItemType.Normal,State=true,Icon="img/jf_baomingf.png",sort=3,appid=3,reg_time=DateTime.Now}, new fee_item(){name="保险费",code="pow",type= feeItemType.Normal,State=false,Icon="img/jf_baox.png",sort=4,appid=4,reg_time=DateTime.Now}, new fee_item(){name="住宿费",code="pow",type= feeItemType.Normal,State=true,Icon="img/jf_dianf.png",sort=5,appid=5,reg_time=DateTime.Now} }; List<school_power> con_power = new List<school_power>() { new school_power(){oid=1,power_code="ykt",power_id="1",reg_time=DateTime.Now}, new school_power(){oid=1,power_code="sims",power_id="2",reg_time=DateTime.Now} }; fim.ForEach(o => context.fee_item.Add(o)); context.SaveChanges(); }View Code
public class FeeDbContext : DbContext { public FeeDbContext() : base("FeeDbContext") { } public DbSet<fee_item> fee_item { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } }View Code
public bool Build() { try { var context = new FeeDbContext(); if (!context.Database.Exists()) { new List<IDataInitializer<FeeDbContext>>() { new DataInit4dept() }.Setup<FeeDbContext>(context); return true; } return false; } catch (DbEntityValidationException ex) { StringBuilder error = new StringBuilder(); foreach (var item in ex.EntityValidationErrors) { foreach (var item2 in item.ValidationErrors) { error.Append(string.Format("{0}:{1}\r\n", item2.PropertyName, item2.ErrorMessage)); } } Console.WriteLine("数据库初始化报错:" + error); throw ex; } catch (Exception e) { Console.WriteLine("数据库初始化报错:" + e.Message); throw e; } }View Code
public bool Remove() { var context = new FeeDbContext(); try { if (context.Database.Exists()) { return context.Database.Delete(); } return true; } catch (Exception e) { Console.WriteLine("数据库初始化报错:" + e.Message); return false; } finally { context.Dispose(); } }View Code
public bool Rebuild() { return Remove() && Build(); }View Code
EF code first 创建和初始化数据库
标签: