首先配置好web.config

<connectionStrings>
<add name="BookDbContext" connectionString=" Data Source=.\SQLEXPRESS;Initial Catalog=sales;Persist Security Info=True;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>

  

然后在Model里添加一个 实体 类和一个实体DbContext类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace MvcApplication3.Models
{
public class Book
{
public int BookID { get; set; }
public string BookName { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public decimal Price { get; set; }
public string Remark { get; set; }
}
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity; namespace MvcApplication3.Models
{
/// <summary>
/// BookDbContext代表EF中Book在数据库中的上下文对象,通过DbSet<Book>使实体类与数据库关联起来。Books属性表示数据库中的数据集实体,用来处理数据的存取与更新。BookDbContext派生自DbContext,需要添加System.Data.Entity的引用。
/// </summary>
public class BookDbContext:DbContext
{
/// <summary>
/// 表示用于执行创建、读取、更新和删除操作的类型化实体集。DbSet 不是公共可构造的,只能从 System.Data.Entity.DbContext实例创建。
/// </summary>
public DbSet<Book> Books { get; set; }
}
}

  

加一个Book控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication3.Models; namespace MvcApplication3.Controllers
{
public class BookController : Controller
{
//
// GET: /Book/ BookDbContext db = new BookDbContext(); /// <summary>
/// //查询出所有的Book对象,组成一个Books,让它展示在页面首页
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
//这是一个简单的Linq查询,在对数据库进行操作时,EF会检查当前的数据连接指定的数据库是否被创建,如果没有则有EF负责根据实体模型类创建数据库、数据表;如果存在,EF会将查询条件添加到Sql查询语句,再将Sql语句发送到数据库进行数据读取。在完成数据读取后,将数据转换为实体对象集合。EF对数据库的操作大致如此
var books = from b in db.Books
select b;
return View(books.ToList());
} [HttpGet]
public ActionResult Create()
{
return View();
} [HttpPost]
public ActionResult Create(Book book)
{ //MVC验证中所有属性验证成功ModelState.IsValid等于true,只要有一个验证不成功ModelState.IsValid就等于false 所以我们可以通过该属性来判断数据的有效性,但有时在数据验证时有时我们不需要验证所有的数据,比如登录时只需要验证用户名及密码格式是否输入正确即可。使用以下方法可以排除要验证的字段:ModelState.Remove("Email");不验证Email。这样Email这个字段就不会被验证了,Email验证不通过ModelState.IsValid的值仍然是true if (ModelState.IsValid)
{
db.Books.Add(book);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View(book);
} }
[HttpGet]
public ActionResult Delete(int id)
{
var data = from DataItem in db.Books
where DataItem.BookID == id
select DataItem;
ViewData.Model = data.Single();
return View();
} [HttpPost]
public ActionResult Delete(int id, FormCollection c) //其实这的FormCollection c 换成 int a=5 或者 int a=6 都是可以的。只要保证这个Delete方法与上面的Delete方法参数不同就可以了。其实也就是保证两个方法构成重载
{
//Find()是返回满足条件的第一个元素,如果没有该元素,则返回null。
Book book = db.Books.Find(id); //也可以写成:Book book=db.Books.FirstOrDefault(d=>d.BookID==id)
db.Books.Remove(book);
db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Edit(int id)
{
//var data = from dataitem in db.Books
// where dataitem.BookID == id
// select dataitem;
//ViewData.Model = data.Single();
//return View(); //Find()是返回满足条件的第一个元素(即:Books中 BookID的的值为id的Book),如果没有该元素,则返回null。
Book book = db.Books.Find(id);
if (book == null)
{
return RedirectToAction("Index");
}
return View(book); }
[HttpPost]
public ActionResult Edit(Book newbook)
{
try
{
Book oldbook = db.Books.Find(newbook.BookID); //使用来自控制器的当前值提供程序的值更新指定的模型实例
UpdateModel(oldbook); //将在此上下文中所做的所有更改保存到基础数据库。
db.SaveChanges();
return RedirectToAction("Index"); }
catch (Exception ex)
{
//AddModelError:将指定的错误消息添加到与指定键关联的模型状态字典的错误集合中。
ModelState.AddModelError("", "修改失败,请查看详细错误信息" + ex.Message + ex.StackTrace);
}
return View(newbook);
} public ActionResult Details(int id)
{
//Find()是返回满足条件的第一个元素(即:Books中 BookID的的值为id的Book),如果没有该元素,则返回null。
Book book = db.Books.Find(id);
if (book == null)
{
return RedirectToAction("Index");
}
return View(book);
} }
}

添加数据

@model MvcApplication3.Models.Book  

@{
ViewBag.Title = "Create";
} <h2>增加</h2> @using (Html.BeginForm()) {
@Html.ValidationSummary(true) <fieldset>
<legend>Book</legend> <div class="editor-label">
@Html.LabelFor(model => model.BookName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.BookName)
@Html.ValidationMessageFor(model => model.BookName)
</div> <div class="editor-label">
@Html.LabelFor(model => model.Author)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Author)
@Html.ValidationMessageFor(model => model.Author)
</div> <div class="editor-label">
@Html.LabelFor(model => model.Publisher)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Publisher)
@Html.ValidationMessageFor(model => model.Publisher)
</div> <div class="editor-label">
@Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</div> <div class="editor-label">
@Html.LabelFor(model => model.Remark)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Remark)
@Html.ValidationMessageFor(model => model.Remark)
</div> <p>
<input type="submit" value="增加" />
</p>
</fieldset>
} <div>
@Html.ActionLink("跳转到首页", "Index")
</div> @section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

 删除数据

@model MvcApplication3.Models.Book  

@{
ViewBag.Title = "Delete";
} <h2>Delete</h2> <h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Book</legend> <table>
<tr><th>图书名称:</th><th>@Html.DisplayFor(model => model.BookName)</th></tr>
<tr><th>作者:</th><th>@Html.DisplayFor(model => model.Author)</th></tr>
<tr><th>出版社:</th><th>@Html.DisplayFor(model => model.Publisher)</th></tr>
<tr><th>价格:</th><th>@Html.DisplayFor(model => model.Price)</th></tr>
<tr><th>备注</th><th>@Html.DisplayFor(model => model.Remark)</th></tr>
</table> </fieldset>
@using (Html.BeginForm()) {
<p>
<input type="submit" value="删除" /> |
@Html.ActionLink("跳转到首页", "Index")
</p>
}

  编辑数据

@model MvcApplication3.Models.Book  

@{
ViewBag.Title = "Edit";
} <h2>编辑</h2> @using (Html.BeginForm()) {
@Html.ValidationSummary(true) <fieldset>
<legend>Book</legend> @Html.HiddenFor(model => model.BookID) <div class="editor-label">
@Html.LabelFor(model => model.BookName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.BookName)
@Html.ValidationMessageFor(model => model.BookName)
</div> <div class="editor-label">
@Html.LabelFor(model => model.Author)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Author)
@Html.ValidationMessageFor(model => model.Author)
</div> <div class="editor-label">
@Html.LabelFor(model => model.Publisher)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Publisher)
@Html.ValidationMessageFor(model => model.Publisher)
</div> <div class="editor-label">
@Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</div> <div class="editor-label">
@Html.LabelFor(model => model.Remark)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Remark)
@Html.ValidationMessageFor(model => model.Remark)
</div> <p>
<input type="submit" value="保存" />
</p>
</fieldset>
} <div>
@Html.ActionLink("跳转到首页", "Index")
</div> @section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

  显示明细

@model MvcApplication3.Models.Book  

@{
ViewBag.Title = "Details";
} <h2>Details</h2> <fieldset>
<legend>Book</legend>
<table>
<tr><th>图书名称:</th><th>@Html.DisplayFor(model => model.BookName)</th></tr>
<tr><th>作者:</th><th>@Html.DisplayFor(model => model.Author)</th></tr>
<tr><th>出版社:</th><th>@Html.DisplayFor(model => model.Publisher)</th></tr>
<tr><th>价格:</th><th>@Html.DisplayFor(model => model.Price)</th></tr>
<tr><th>备注</th><th>@Html.DisplayFor(model => model.Remark)</th></tr>
</table>
</fieldset>
<p>
@Html.ActionLink("编辑", "Edit", new { id=Model.BookID }) |
@Html.ActionLink("跳转到首页", "Index")
</p>

  

MVC Code First(数据模型实例讲解)的更多相关文章

  1. ASP.NET MVC 5 - 给数据模型添加校验器

    在本节中将会给Movie模型添加验证逻辑.并且确保这些验证规则在用户创建或编辑电影时被执行. 拒绝重复 DRY ASP.NET MVC 的核心设计信条之一是DRY: "不要重复自己(DRY ...

  2. 【MySQL】分页查询实例讲解

    MySQL分页查询实例讲解 1. 前言 本文描述了团队在工作中遇到的一个MySQL分页查询问题,顺带讲解相关知识点,为后来者鉴.本文的重点不是"怎样"优化表结构和SQL语句,而是探 ...

  3. 这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解)(转)

    前言 在Andrroid开发中,网络请求十分常用 而在Android网络请求库中,Retrofit是当下最热的一个网络请求库 今天,我将献上一份非常详细Retrofit v2.0的使用教程,希望你们会 ...

  4. [转]ASP.NET MVC 5 - 给数据模型添加校验器

    在本节中将会给Movie模型添加验证逻辑.并且确保这些验证规则在用户创建或编辑电影时被执行. 拒绝重复 DRY ASP.NET MVC 的核心设计信条之一是DRY: "不要重复自己(DRY  ...

  5. 这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解)

    前言 在Andrroid开发中,网络请求十分常用 而在Android网络请求库中,Retrofit是当下最热的一个网络请求库 今天,我将献上一份非常详细Retrofit v2.0的使用教程,希望你们会 ...

  6. jQuery.uploadify文件上传组件实例讲解

    1.jquery.uploadify简介 在ASP.NET中上传的控件有很多,比如.NET自带的FileUpload,以及SWFUpload,Uploadify等等,尤其后面两个控件的用户体验比较好, ...

  7. ContentProvider数据库共享之——实例讲解

      版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/harvic880925/article/details/44591631 前言:现在这段时间没这 ...

  8. 实例讲解Springboot整合MongoDB进行CRUD操作的两种方式

    1 简介 Springboot是最简单的使用Spring的方式,而MongoDB是最流行的NoSQL数据库.两者在分布式.微服务架构中使用率极高,本文将用实例介绍如何在Springboot中整合Mon ...

  9. float实例讲解

    float实例讲解 float是个强大的属性,在实际前端开发过程中,人们经常拿它来进行布局,但有时,使用的不好,也麻烦多多啊. 比如,现在我们要实现一个两列布局,左边的列,宽度固定:右边的列,宽度自动 ...

随机推荐

  1. 解题笔记-洛谷-P1010 幂次方

    0 题面 题目描述 任何一个正整数都可以用2的幂次方表示.例如 137=2^7+2^3+2^0 同时约定方次用括号来表示,即a^b 可表示为a(b). 由此可知,137可表示为: 2(7)+2(3)+ ...

  2. Web Fragment在项目中的使用

    Web Fragment 是什么 - 它是在 servlet 3.0开始支持的,可以把一个dy web项目拆分为多个项目,解耦合,使其在项目中开发效率提高,下面我演示简单的项目创建过程 用eclips ...

  3. [js插件开发教程]实现一个比较完整的开源级选项卡插件

    在这篇文章中,我实现了一个基本的选项卡功能:请猛击后面的链接>>   [js插件开发教程]原生js仿jquery架构扩展开发选项卡插件. 还缺少两个常用的切换(自动切换与透明度渐变),当然 ...

  4. LINUX 笔记-find 命令常用用法

    命令格式: find path -option [-print] [-exec -ok] -print:find 命令将匹配的文件输出到标准输出 -exec:find 命令对匹配的文件执行该参数所给出 ...

  5. 使用Aspose.Cells利用模板导出Excel(C#)

    前言 随着互联网的流行,web项目逐渐占据主流.我相信大部分人开发项目的过程中都写过上传以及导出Excel和Word的功能,本文仅讨论导出Excel.C#中有很多第三方组件支持导出Excel,比如:N ...

  6. AsyncTask学习

    在学习Android的时候,开始用到比较多的异步处理的类大概就是AsyncTask,但是我们很多时候只知道调用,却不知道思考一些东西. 本文就简单的总结和分析了一些AsyncTask的知识. 一.As ...

  7. SQL数据查询语句(一)

    本文所用数据库为db_Test,数据表为Employee 一.SELECT语句基本结构 语句语法简单归纳为: SELECT select_list [INTO new_table_name] [FRO ...

  8. iOS 之 runtime --- 集百家之言

    runtime runtime用在什么地方? 说法 在程序运行过程中,动态的创建一个类(比如KVO的底层实现) 在程序运行过程中,动态地为某个类添加属性.方法,修改属性值\方法(method swiz ...

  9. 关于C#开发中那些编码问题

    最近一直在搞各种编码问题,略有心得,与大家分享一番. System.Text提供了Encoding的抽象类,这个类提供字符串编码的方法.常用的编码方式主要有ASCII,Unicode,UTF8(Uni ...

  10. linux学习(五)系统目录结构,ls命令,文件类型,alias

    一.系统目录结构 在我们的根目录下,有这样一些文件夹 /bin /sbin /usr/bin /usr/sbin /sbin一般都是root用户用的 /boot 系统启动相关的,grup就放在这里,这 ...