首先配置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里加入一个Book 类和一个BookDbContext类

Book类

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; }
}
}

BookDbContext类

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控制器

要了解FormCollection请參考:FormCollection传值

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 所以我们能够通过该属性来推断数据的有效性,但有时在数据验证时有时我们不须要验证全部的数据,比方登录时仅仅须要验证username及password格式是否输入正确就可以。使用下面方法能够排除要验证的字段: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);
} }
}

view

Index 视图 首页

@model IEnumerable<MvcApplication3.Models.Book>
@{
ViewBag.Title = "图书列表-MvcBook";
}
<h2>
图书列表</h2>
<p>
@Html.ActionLink("添加图书", "Create")
</p>
<table>
<tr>
<th>图书名称</th><th>作者</th><th>出版社</th><th>价格</th><th>备注</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.BookName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.Publisher)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Remark)
</td>
<td>
@Html.ActionLink("编辑", "Edit", new { id = item.BookID }) |
@Html.ActionLink("具体", "Details", new { id = item.BookID }) |
@Html.ActionLink("删除", "Delete", new { id = item.BookID })
</td>
</tr>
}
</table>

Create

@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")
}

Delete

@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>
}

Edit

@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")
}

Details

@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. EF之Code First代码优先

    1.前言 通过英文可知,表示的是代码优先,一般创建EF都是先创建数据库,创建根据数据库的EF实体模型,而code - first 则是反过来!... 2.代码实战 我们这次创建的不是原来的数据库EF设 ...

  2. MVC中EF代码优先问题

    在练习Mvc项目时,提示如下数据库错误: The model backing the 'EFDbContext' context has changed since the database was ...

  3. 结合实体框架(代码优先)、工作单元测试、Web API、ASP. net等,以存储库设计模式开发示例项目。NET MVC 5和引导

    介绍 这篇文章将帮助你理解在库模式.实体框架.Web API.SQL Server 2012.ASP中的工作单元测试的帮助下设计一个项目.净MVC应用程序.我们正在开发一个图书实体和作者专用的样例图书 ...

  4. 代码优先-Code First

    非常有用的两篇文章 MSDN:Code First 迁移 博客园:CodeFirst数据迁移(不丢失数据库原有数据) EF有三种开发模式:Model First,Database First 和 Co ...

  5. C# ORM—Entity Framework 之Code first(代码优先)(二)

    一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...

  6. 七:mvc使用CodeFirst(代码优先)创建数据库

    1. 理解EF CodeFirst模式特点 2. 使用CodeFirst模式生成数据库 1. CodeFirst模式(代码优先) Code First是Entity Framework提供的一种新的编 ...

  7. EF Code First 使用 代码优先迁移(三)

    迁移到特定版本(包括降级) 到目前为止,我们一直升级到最新的迁移,但有时您可能需要升级/降级到特定的迁移. 这是目前我数据库中的表:有四个表,我降级到addEndTime这个版本(这个版本是没有gra ...

  8. 从实体框架核心开始:构建一个ASP。NET Core应用程序与Web API和代码优先开发

    下载StudentApplication.Web.zip - 599.5 KB 下载StudentApplication.API.zip - 11.5 KB 介绍 在上一篇文章中,我们了解了实体框架的 ...

  9. 使用Entity Framework 4进行代码优先开发

    [原文地址]Code-First Development with Entity Framework 4   .NET 4随带发布了一个改进版的Entity Framework(EF)- 一个位于Sy ...

随机推荐

  1. FZU2179(数位dp)

    传送门:Chriswho 题意:求区间[1,n]内能整除自己本身各位数字的数的个数. 分析:这题跟CF 55D Beautiful numbers一样的,一个数能被它的所有非零数位整除,则能被它们的最 ...

  2. HDU 4643 GSM 简单计算几何

    今天比赛的时候略坑, admin告诉我询问Q的个数不超过n^2, 赛后敲了个 O(Q*m^3)的复杂度,但这个复杂度常数比较低,可能在除以个小常数, 300ms过了,真心无语,数据应该水了吧,比赛的时 ...

  3. Android设备管理器漏洞2--禁止用户取消激活设备管理器

    2013年6月,俄罗斯安全厂商卡巴斯基发现了史上最强手机木马-Obad.A.该木马利用了一个未知的Android设备管理器漏洞(ANDROID-9067882),已激活设备管理器权限的手机木马利用该漏 ...

  4. hdu3038(并查集)

    题目链接 题意:有n次询问,给出a到b区间的总和,问这n次给出的总和中有几次是和前面已近给出的是矛盾的 分析:sum数组维护着到根节点的距离(即区间和),每次合并x,y,s(a,b分别为x,y的根节点 ...

  5. 采用CXF+spring+restful创建一个web接口项目

    这篇文章是http://blog.csdn.net/zxnlmj/article/details/28880303下面,加入的基础上的restful特征 1.参加restful必jar包裹 jsr31 ...

  6. 前端控件之Jquery datetimepicker的使用总结

    效果图 在介绍jquery datetimepicker的使用方法前,我们先来看一下它的实现效果图,这样以便让你更快地了解它是否是你所需要的. 下面我截了四张常用的效果图(截取自http://xdso ...

  7. 使用异步HTTP提升客户端性能(HttpAsyncClient)

    使用异步HTTP提升客户端性能(HttpAsyncClient) 大家都知道,应用层的网络模型有同步.异步之分. 同步,意为着线程阻塞,只有等本次请求全部都完成了,才能进行下一次请求. 异步,好处是不 ...

  8. apache2.4.4启用deflate压缩

    今天在看<高性能php应用开发>这本书,说道如何启用mod_deflate: 启用如下模块: LoadModule deflate_module modules/mod_deflate.s ...

  9. 工厂方法模式(factory method pattern)

    工厂方法模式相对于简单工厂模式的长处是为了更好的拓展,当假设再新加一种产品,对于简单工厂模式来说须要改动核心的工厂类,但对于工厂方法模式则不须要,在工厂方法模式中核心的工厂类不再负责创建全部产品的创建 ...

  10. 我写了一起 Makefile(一)

    我写了一起 Makefile  陈皓 概述—— 什么是makefile?也许非常多Winodws的程序猿都不知道这个东西,由于那些Windows的IDE都为你做了这个工作.但我认为要作一个好的和pro ...