在上一篇文章中,我们已经把Model层搭建好了,那么接上来我就为大家讲一下怎么通过code first创建对应的数据库:
1:首先我们建一个类继承Dbcontext,用于对数据库的操作
在DAL层中建一个类名字可以随意,我图方便也命名成了DbContext
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Model;
namespace DAl
{
public class DbContext : System.Data.Entity.DbContext
{
private static string dbName = System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString();//这个有另一中写的方式个人习惯这样
public DbContext()
: base(dbName)
{
Database.SetInitializer<DbContext>(new CreateDatabaseIfNotExists<DbContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//表名不用复数形式
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
//放置的是数据库对应的实体对象
public DbSet<IndexActice> IndexActice { get; set; }
}
}
2:既然上文中使用webconfig的链接字符串那么就先到webconfig中设置一下
<connectionStrings>
<add name="conn" connectionString="Data Source=.;User ID=sa;database=数据名;Password=.." />
</connectionStrings>
3:增加一个类用于填充数据库数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using Model;
namespace DAl
{
public class BaseInitializer : DropCreateDatabaseIfModelChanges<DbContext>
{
protected override void Seed(DbContext context)
{
var Index = new List<IndexActice>
{
new IndexActice{acticeName="小明",remarkMes="sdsadsadsd",userID=12545},
new IndexActice{acticeName="小ds",remarkMes="dsaaa",userID=5522}
};
Index.ForEach(s => context.IndexActice.Add(s));
context.SaveChanges();
}
}
}
4:在控制器中初始化这个model的数据
//需要添加引用using System.Data.Entity;
public ActionResult acticeMes()
{
DAl.DbContext db = new DAl.DbContext();
Database.SetInitializer<DAl.DbContext>(new BaseInitializer());
return View(db.IndexActice.ToList());
}
5:在视图中调用数据
@{
ViewBag.Title = "acticeMes";
Layout = "";
}
@using Model;
@model IEnumerable<IndexActice>
@foreach (var a in Model)
{
<h2>@a.ID</h2>
<h2>@a.acticeName</h2>
<h2>@a.acticeMes</h2>
<h2>@a.userID</h2>
}
数据库到这里就已经建好了但有一个问题是如果model成的结构改变,那么就必须删除除数据库重建,这样会造成的数据的丢失!解决的办法是把codefirst的数据迁移打开:
1:打开程序控制台:输入Enable-Migrations,运行结束后会自动生成一个Migrations文件夹,打开里面的Configuration.cs类找到下面的方法把AutomaticMigrationsEnabled 打开
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "DAL.DbContext";
}
2:如果有需要有model结构改变时在程序控制台中输入:Update-Database -Force,这样数据库的结构会改变,而且数据不会丢失!