MVC Code First(数据模型实例讲解)
首先配置好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(数据模型实例讲解)的更多相关文章
- ASP.NET MVC 5 - 给数据模型添加校验器
在本节中将会给Movie模型添加验证逻辑.并且确保这些验证规则在用户创建或编辑电影时被执行. 拒绝重复 DRY ASP.NET MVC 的核心设计信条之一是DRY: "不要重复自己(DRY ...
- 【MySQL】分页查询实例讲解
MySQL分页查询实例讲解 1. 前言 本文描述了团队在工作中遇到的一个MySQL分页查询问题,顺带讲解相关知识点,为后来者鉴.本文的重点不是"怎样"优化表结构和SQL语句,而是探 ...
- 这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解)(转)
前言 在Andrroid开发中,网络请求十分常用 而在Android网络请求库中,Retrofit是当下最热的一个网络请求库 今天,我将献上一份非常详细Retrofit v2.0的使用教程,希望你们会 ...
- [转]ASP.NET MVC 5 - 给数据模型添加校验器
在本节中将会给Movie模型添加验证逻辑.并且确保这些验证规则在用户创建或编辑电影时被执行. 拒绝重复 DRY ASP.NET MVC 的核心设计信条之一是DRY: "不要重复自己(DRY ...
- 这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解)
前言 在Andrroid开发中,网络请求十分常用 而在Android网络请求库中,Retrofit是当下最热的一个网络请求库 今天,我将献上一份非常详细Retrofit v2.0的使用教程,希望你们会 ...
- jQuery.uploadify文件上传组件实例讲解
1.jquery.uploadify简介 在ASP.NET中上传的控件有很多,比如.NET自带的FileUpload,以及SWFUpload,Uploadify等等,尤其后面两个控件的用户体验比较好, ...
- ContentProvider数据库共享之——实例讲解
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/harvic880925/article/details/44591631 前言:现在这段时间没这 ...
- 实例讲解Springboot整合MongoDB进行CRUD操作的两种方式
1 简介 Springboot是最简单的使用Spring的方式,而MongoDB是最流行的NoSQL数据库.两者在分布式.微服务架构中使用率极高,本文将用实例介绍如何在Springboot中整合Mon ...
- float实例讲解
float实例讲解 float是个强大的属性,在实际前端开发过程中,人们经常拿它来进行布局,但有时,使用的不好,也麻烦多多啊. 比如,现在我们要实现一个两列布局,左边的列,宽度固定:右边的列,宽度自动 ...
随机推荐
- mb_substr函数
定义和用法 mb_substr() 截取字符串中指定长度字符 注:常用于中文截取,可以避免截取时候出现乱码,即截取半个字符的情况. 类似函数 substr(),iconv_substr() 语法 mb ...
- (MariaDB)MySQL数据类型详解和存储机制
html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...
- LeetCode 581. Shortest Unsorted Continuous Subarray (最短无序连续子数组)
Given an integer array, you need to find one continuous subarray that if you only sort this subarray ...
- Max Sum Plus Plus
A - Max Sum Plus Plus Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I6 ...
- 注销/etc/passwd带来的系统登陆不上
今天在修改虚拟机密码上的时候,将/etc/passwd中root所在的哪行注销掉了,想象是注销了,root登陆时应该不要输入密码,结果是系统进度条走到最后的时候 进入不了系统了. 结果去普及了下/et ...
- SVN提交文件的时候过滤指定文件
如果使用TortoiseSVN作为客户端的话,可以在TortoiseSVN右键菜单中的 "设置"(settings)--常规设置(General)--全局忽略样式里设置(Globa ...
- ldap数据库--ODSEE--suffix
ldap数据库的suffix是建立ldap之间复制协议的基础,suffix的创建也可以通过管理界面进行,也可以通过命令行进行.不同点是通过管理界面创建的suffix会自动创建一条对应该suffix的匿 ...
- Python 面向对象基础知识
面向对象基础知识 1.什么是面向对象编程? - 以前使用函数 - 类 + 对象 2.什么是类什么是对象,又有什么关系? class 类: def 函数1(): pass def 函数2(): pass ...
- 一:详解 HTTP 协议
本篇文章篇幅比较长,先来个思维导图预览一下. 一张图带你看完本篇文章 一.概述 1.计算机网络体系结构分层 计算机网络体系结构分层 2.TCP/IP 通信传输流 利用 TCP/IP 协议族进行网络通信 ...
- Velocity(1)——初步入门
1.变量 (1)变量的定义: 1 #set($name = "hello") 说明:velocity中变量是弱类型的. 2 3 当使用#set 指令时,括在双引号中的字面字符串将解 ...