MVC中code first数据库的生成

在上一篇文章中,我们已经把Model层搭建好了,那么接上来我就为大家讲一下怎么通过code first创建对应的数据库:

1:首先我们建一个类继承Dbcontext,用于对数据库的操作
在DAL层中建一个类名字可以随意,我图方便也命名成了DbContext
DAL层

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,这样数据库的结构会改变,而且数据不会丢失!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值