先要链接同mysql ,具体看这篇文章https://user.qzone.qq.com/450538150/blog/1520847821 引入以下文件![]() 测试目录: ![]() 先创建个Admin model
/// <summary>
/// 管理员表
/// </summary>
[Table("s_Admin")]
public partial class Admin
{
[Key]//标示为 主键
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[MaxLength(30)]
public string UserName { get; set; }
[MaxLength(50)]
public string PassWord { get; set; }
}
然后创建BaseContext类
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
//[DbConfigurationType(typeof(DbContextConfiguration))]
public class BaseContext : DbContext
{
public BaseContext()
: base("name=webconfig数据库配置名")
{
}
public DbSet<Admin> Admin { get; set; }//引入表
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
然后创建
public class SendDataBase : CreateDatabaseIfNotExists<BaseContext>
{
public SendDataBase(){
BaseContext context = new BaseContext();
base.Seed(context);
SqlHelper<Admin> dal = new SqlHelper<Admin>();//这里相当于dal类
dal.GetModel(o => o.ID == 1);//这里获取个model或者添加个model都可以,不想要添加默认数据用获取个model
//dal.Add(new Admin { PassWord = "123", UserName = "123", Status = 1 });
//dal.Add(new Admin { LastLoginTime = DateTime.Now, PassWord = "123", UserName = "123" });
//dal.Add(new Admin { LastLoginTime = DateTime.Now, PassWord = "123", UserName = "123"});
//dal.SaveChanges();
} }
1、CreateDatabaseIfNotExists:在没有数据库时创建一个,这是默认行为。 2、DropCreateDatabaseIfModelChanges:模型改变时,自动重新创建一个新的数据库,就可以用这个方法。在这开发过程中非常有用。 3、DropCreateDatabaseAlways:每次运行时都重新生成数据库。 最后在Global插入 Database.SetInitializer(new SendDataBase());
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
Database.SetInitializer(new SendDataBase());
}
|
转载于:https://www.cnblogs.com/xiaozhazhazha/p/8564481.html