一,在models文件夹中,建立相应的model文件
        这里注意一点,这里建立的class名,就是数据库里表的名字。
        在这里面,可以建立表之间的关系。

这里要说明一点的事,一般情况下,我们会把n:m的形式,变成两个1:n的模式

  //学生信息
namespace codefirst.Models
{
public class Students
{
public int ID { get; set; } [Required]
[MaxLength(10)]
public string stu_Name { get; set; } public string stu_Pwd { get; set; } public string stu_sex { get; set; } public int stu_age { get; set; } public virtual ICollection<StuCousers> StuCousers { get; set; }
}
} //课程信息
namespace codefirst.Models
{
public class Courses
{
public int ID { get; set; } public string course_Name { get; set; } public string course_code { get; set; } public virtual ICollection<StuCousers> StuCousers { get; set; }
}
} //学生课程关联表
namespace codefirst.Models
{
public class StuCousers
{
public int ID { get; set; } public int StudentID { get; set; } public int CourseID { get; set; } public virtual Students Student { get; set; } public virtual Courses Course { get; set; }
}
}

二,新建一个Dal文件夹,用来建立Database Context

    namespace codefirst.DAL
{
public class BaseContext : DbContext
{ /// <summary>
/// 构造函数中的 base("AccountContext") 。
/// 默认情况下和类名一样,即AccountContext,我们显式的给他指定出来。
/// </summary>
public BaseContext()
: base("BaseContext")
{ } public DbSet<Students> Students { get; set; } public DbSet<Courses> Courses { get; set; } public DbSet<StuCousers> StuCousers { get; set; } /// <summary>
/// 指定单数形式的表名
/// 默认情况下会生成复数形式的表,如SysUsers
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}

这里面DbSet对应着数据库里表

三,初始化数据库与表

第一次运行程序时新建数据库,插入测试数据; model改变(和database不一致)时删除重建数据库,插入测试数据。
先不用管数据丢失的问题,直接drop and re-create比较方便。

       namespace codefirst.DAL
{
public class BaseInitializer : DropCreateDatabaseIfModelChanges<BaseContext>
{
protected override void Seed(BaseContext context)
{
var stu = new List<Students>
{
new Students{stu_Name="小明",stu_Pwd="123456",stu_sex="男"},
new Students{stu_Name="小芳",stu_Pwd="654321",stu_sex="女"}
}; stu.ForEach(s => context.Students.Add(s));
context.SaveChanges(); var cou = new List<Courses>
{
new Courses{course_Name="语文",course_code="10001"},
new Courses{course_Name="数学",course_code="10002"}
}; cou.ForEach(c => context.Courses.Add(c));
context.SaveChanges();
}
}
}

四,修改根目录下面的Web.config文件,添加

    <connectionStrings>
<add name="BaseContext" connectionString="Data Source=.;database=StuAndCourse;uid=sa;pwd=xxxxxxx;AttachDBFilename=|DataDirectory|\StuAndCourse.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>

这样,会在App_Data文件夹下生成名为StuAndCourse的数据库

五,在Global.asax文件,添加创建语句

 protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes); //添加建表
Database.SetInitializer<BaseContext>(new BaseInitializer());
}

六,建立Controllers文件,向前台输出数据

 namespace codefirst.Controllers  

   public class StudentController : Controller
{ BaseContext db = new BaseContext(); // GET: Student
public ActionResult Index()
{
return View(db.Students.ToList());
}
}

七,建立Views文件,用来显示数据

    @model IEnumerable<codefirst.Models.Students>
@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.stu_Name)
</td>
<td>
@foreach(var sc in item.StuCousers)
{
@Html.Label(sc.Course.course_Name)
}
</td>
</tr>
}
</table>
</div>
</body>
</html>

好,现在运行程序,你会发现,数据显示出来了,而且数据库也建立成功了。这里为什么要有第六,七步呢,因为你要有一个操作数据库的代码,它才会去建数据库。

下面我们再来看一下,如果我修改了Models中的文件,使得SysUser与数据库中的SysUser表的字段不一样了,这样如果我再运行程序,你会发现数据库被重置了。
这为什么呢,还记得第三步吗,这里就是如果结构不一定,就会删除再生成表。
可是我们在开始的过程中,有一些数据,不希望丢怎么办呢。

工具 -> 库程序包管理器 -> 程序包管理器控制台
运行命令 Enable-Migrations
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded
migration '201212090821166_InitialCreate' corresponding to existing
database. To use an automatic migration instead, delete the Migrations
folder and re-run Enable-Migrations specifying the
-EnableAutomaticMigrations
parameter.

会出现,上面这个错误。不用管它,这时候,你会发现在程序端多出一个文件夹叫Migrations
这里面有一个Configuration.cs文件
打开它,然后修改成如下样子,
public Configuration()
{
AutomaticMigrationsEnabled = true; //这里变成true
ContextKey = "codefirst.DAL.BaseContext";
}

修改完成后,运行
Update-Database -Force这个时候,你再看一下数据库里面的表结构是不是变了,而数据却没有丢呢.

以后再有更改,只要保证Configuration.cs文件中的AutomaticMigrationsEnabled = true;
只运行Update-Database -Force就可以了

转自:https://blog.csdn.net/chenguang79/article/details/50847550

【转】MVC中code first方式开发,数据库的生成与更新(Ef6)的更多相关文章

  1. MVC中code first方式开发,数据库的生成与更新

    在使用EF的实际编程中我们经常遇到这样的问题:发现实体结构需要新增加一个字段,或者减少一个字段,急需把实体结构修改,并让数据库更新这种修改.在用Model First或者Database First的 ...

  2. 在ASP.NET MVC中以post方式传递数组参数的示例

    最近在工作中用到了在ASP.NET MVC中以post方式传递数组参数的情况,记录下来,以供参考. 一.准备参数对象 在本例中,我会传递两个数组参数:一个字符串数组,一个自定义对象数组.这个自定义对象 ...

  3. Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法

    Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法 在Action中方法的返回值都是字符串行,一般情况是返回某个JSP,如: return "xx" ...

  4. 在ASP.NET MVC中以post方式传递数组参数的示例【转】

    最近在工作中用到了在ASP.NET MVC中以post方式传递数组参数的情况,记录下来,以供参考. 一.准备参数对象 在本例中,我会传递两个数组参数:一个字符串数组,一个自定义对象数组.这个自定义对象 ...

  5. IOC容器-Autofac在MVC中实现json方式注入使用

    在你阅读时,默认已经了解IOC和autofac的基本用法, 我在最近的我的博客项目中运用了IOC autofac 实现了依赖注入 由于我的项目时asp.net MVC所以我目前向大家展示MVC中如何使 ...

  6. ios开发数据库版本迁移手动更新迭代和自动更新迭代艺术(二)

    由于大家都热衷于对ios开发数据库版本迁移手动更新迭代和自动更新迭代艺术(一)的浏览下面我分享下我的源文件git仓库: 用法(这边我是对缓存的一些操作不需要可以省去):https://github.c ...

  7. MVC中使用JQuery方式进行异步请求和使用自带方式进行异步请求

    在MCV中使用异步请求可以很很高效地进行前台和后台的数据传递,在这里,笔者为初学者介绍两种在MVC中常用的异步请求处理方式. 在这里,我们通过在一个页面中放置一个按钮来异步获取当前服务器端的系统时间为 ...

  8. MVC中关于Membership类跟数据库的问题

    Membership它们用的是ASPNETDB这个数据库,但我们可以使用我们自定义的数据库,然而除非我们自定义的数据库有着跟这个ASPNETDB一样的模式,否则ASP.NET提供的默认的SqlMemb ...

  9. MVC中页面传值方式总结

    MVC中的页面传值,通常指Controller和view之间的数据传递,经常用到的有几种方式,总结如下: 一.Controller----------->View(控制器传到视图) 1.View ...

随机推荐

  1. VR外包团队:魔幻的三星GearVR

    如果问大大菌,移动端什么产品最好,大大菌一定会和你说,是gearvr,对于已经购买了三星2015旗舰手机.又对VR技术感到好奇的用户,建议花99美元买一台Gear VR,绝对会让你物有所值. 在短短的 ...

  2. svn的使用教程

    引言:这里只讲解几个svn不常用但是非常有用的使用方法,对于经常使用的不做概述,因为很简单,而且网上都能找到. 1.1 svn历史版本对比已经恢复到指定版本(myeclipse) 在项目中的文件或者文 ...

  3. VC.判断双字节字符集前导字节集(IsDBCSLeadByte)

    ZC:这是 WIndows API 函数 1.“BOOL IsDBCSLeadByte( char );” 判断 某字节是否在 双字节字符集的前导字节集中 ZC:可以判断  如 汉字.日文.韩文等 Z ...

  4. vue定义全局方法 调用其他组件的方法

    官网的写法  vue实例.$on就可以在根实例上定义全局方法 this.$root就是获取根实例  如果没有根实例 就表示当前实例 this.$root.$on 不需要.eventHub 不需要下面这 ...

  5. 学习笔记46—如何使Word和EndNote关联

    1)打开Word文件项目中的选项,然后点击加载项, 2)找到Endnote安装目录,选择目录中的Configure EndNote.exe,选中configuration endnote compon ...

  6. Mac Anaconda 安装

    下载地址 https://www.anaconda.com/download/#macos 选择对应的python 版本 安装 一路下一步 安装后打开如下 呵呵,此处装完,我的python 环境又从3 ...

  7. Unity --- sharedMaterial 、material

    sharedMaterial: 无论如何更新材质的属性,内存中只会存在一份. material: 每次更新材质属性的时候,内存中都会重新new一份material作用于它,直到 Application ...

  8. [Spring] Aspect Oriented Programming with Spring | AOP | 切面 | 切点

    使用Spring面向切面编程 1.介绍 AOP是OOP的补充,提供了另一种关于程序结构的思路. OOP的模块化的关键单位是 类 . AOP的则是aspect切面. AOP 将程序的逻辑分成独立的块(叫 ...

  9. Maven报错Please ensure you are using JDK 1.4 or above and not a JRE解决方法!

    https://www.cnblogs.com/shihua513/p/6163682.html 在eclipse下用maven编译时,很有可能出现以下错误: Please ensure you ar ...

  10. spring: beanutils.copyproperties将一个对象的数据塞入到另一个对象中(合并对象)

    spring: beanutils.copyproperties将一个对象的数据塞入到另一个对象中(合并对象) 它的出现原因: BeanUtils提供对Java反射和自省API的包装.其主要目的是利用 ...