1.usingConsoleApplication42;usingSystem.Data.Entity;usingSystem.Data.Entity.ModelConfiguration.Conventions;namespaceConsoleApplication42
{usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations.Schema;usingSystem.Data.Entity;usingSystem.Linq;public classTbUser
{public int Id { get; set; }public string UserName { get; set; }public string Password { get; set; }public string Email { get; set; }public virtual ICollection TbUserRoles { get; set; }
}public classTbRole
{public int Id { get; set; }public string RoleName { get; set; }public string RoleDescription { get; set; }public virtual ICollection TbUserRoles { get; set; }
}public classTbUserRole
{public int Id { get; set; }public int UserId { get; set; }public int RoleId { get; set; }
[ForeignKey("UserId")]public virtual TbUser TbUser { get; set; }
[ForeignKey("RoleId")]public virtual TbRole TbRole { get; set; }
}public classstud
{
}public classMyDbContext : DbContext
{publicMyDbContext()
:base("MyDbContext")
{
}public IDbSet TbUsers { get; set; }public IDbSet TbRoles { get; set; }public IDbSet TbUserRoles { get; set; }protected override voidOnModelCreating(DbModelBuilder modelBuilder)
{//因为表名称默认为复数形式,这里是移除复数形式,所以为单数形式生成
modelBuilder.Conventions.Remove();
}
}//public class MyEntity//{//public int Id { get; set; }//public string Name { get; set; }//}
public class Initializer : CreateDatabaseIfNotExists{public MyDbContext dbContext { get; set; }publicInitializer()
{
}///
///
///
/// 是否初始化数据库数据 默认不初始化表为空
public void InitData(bool initData=false)
{
InitializeDatabase(dbContext);if (!initData)return;
Seed(dbContext);
}public override voidInitializeDatabase(MyDbContext context)
{base.InitializeDatabase(context);
}protected override voidSeed(MyDbContext context)
{var tbUsers = new List{new TbUser{UserName="张三",Password="zhangsan",Email="zhangsan@163.com"},new TbUser{UserName="李四",Password="lisi",Email="lisi@163.com"}
};
tbUsers.ForEach(u=>context.TbUsers.Add(u));var tbRoles = new List{new TbRole{RoleName="管理员",RoleDescription="管理员具有最高权限来对系统进行管理"},new TbRole{RoleName="一般用户",RoleDescription="一般用户具有一些基本的操作权限"}
};
tbRoles.ForEach(r=>context.TbRoles.Add(r));var tbUserRole = new List{new TbUserRole{UserId=1,RoleId=1},new TbUserRole{UserId=1,RoleId=2},new TbUserRole{UserId=2,RoleId=2}
};
tbUserRole.ForEach(ur=>context.TbUserRoles.Add(ur));
context.SaveChanges();
}
}
}2.App.Config配置文件<?xml version="1.0" encoding="utf-8"?>
3.BLL.xml<?xml version="1.0" encoding="utf-8" ?>
4.调用usingSpring.Context;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceConsoleApplication42
{classProgram
{static void Main(string[] args)
{//new Initializer();
var ctx =Spring.Context.Support.ContextRegistry.GetContext();var init =(Initializer) ctx["Initializer"];//初始化数据库或者数据
init.InitData(true);
}
}
}