MVC+EF 入门教程(三)
一、前言
上一节,我们将了生成数据库,那么这张我就将操作设计库。
二、在 Aplication 定义服务
在 Application 中添加文件夹(Blog)和 操作类(BlogServer)。实例如下:

结果有报错,提示是如下:

那么我们的解决方案是:在 Application 中也加入 EntityFramework 的程序集。
在找到 引用 -->管理NuGet重新包 实例如下:


然后安装它,代码就不报错了。

实现对 Blog 的 CRUD 的代码如下:
using Core.Blogs;
using EntityFrameworkDome.EFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Application.Blogs
{
public class BlogServer
{
//获取 Blog 数据
public List<Blog> getBlog()
{
var db = new SQLServerContext();
var data = db.Blogs.ToList<Blog>(); return data;
} //删除 Blog 数据
public Boolean DeleteBlog(int id)
{
Boolean b = false;
var db = new SQLServerContext();
try
{
Blog blog = db.Blogs.Find(id);
db.Blogs.Remove(blog);
db.SaveChanges();
b = true;
}
catch (Exception e) { }
return b;
} //编辑 Blog 数据
public Blog getEditBlog(int id)
{
Blog blog = null;
var db = new SQLServerContext();
blog = db.Blogs.Find(id);
return blog;
} //保存 Blog 数据
public Boolean seveBlog(Blog blog)
{
Boolean b = false;
var db = new SQLServerContext();
try
{
Blog a = db.Blogs.First(r => r.Id == blog.Id);
a.Contect = blog.Contect;
a.Title = blog.Title;
a.CreatedTime = blog.CreatedTime;
db.SaveChanges();
b = true;
}
catch (Exception)
{ throw;
} return b;
} //创建 Blog 数据
public Boolean createNewBlog(Blog blog)
{
Boolean b = false;
var db = new SQLServerContext();
try
{
db.Blogs.Add(blog);
db.SaveChanges();
b = true;
}
catch (Exception e)
{
throw;
}
return b;
}
}
}
服务代码也编写完成,那么我们开始操作服务代码。
三、在 web 中页面实现
在 web 中,首先我们去修改路由,路由在什么地方?这个很好找
web / App_Start / RouteConfig
修改方式如下:

然后再 Controller 中,新建 BlogController 控制器。
具体添加方式:Controllers --> 添加 --> 控制器 --> MVC 5 控制器 - 空
将默认的控制器该为 BlogController
实例如下:

然后在 Index 作用域 中,右键添加 -->添加视图

在BlogController 完成的代码如下:
using Application.Blogs;
using Core.Blogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace Web.Controllers
{
public class BlogController : Controller
{
// GET: Blog
public ActionResult Index(string key)
{
BlogServer db = new BlogServer();
List<Blog> data = db.getBlog(key);
return View(data);
} public ActionResult ErrorPage()
{ return View();
}
public ActionResult CreateBlog()
{
return View();
}
[HttpPost]
public ActionResult CreateNewBlog(string Title, string Contect)
{ Blog b = new Blog();
b.Contect = Request.Form["Contect"];
b.Title = Request.Form["Title"];
b.CreatedTime = System.DateTime.Now;
BlogServer bs = new BlogServer();
if (bs.createNewBlog(b))
{
return RedirectToAction("Index");
}
return RedirectToAction("ErrorPage"); } public ActionResult DeleteBlog(int id)
{
BlogServer db = new BlogServer(); if (db.DeleteBlog(id))
{
return RedirectToAction("Index");
}
return RedirectToAction("ErrorPage");
} public ActionResult getEditBlog(int id)
{
BlogServer db = new BlogServer();
Blog blog = db.getEditBlog(id);
return View(blog);
} [HttpPost]
public ActionResult seveBlog(Blog b)
{
BlogServer db = new BlogServer();
if (db.seveBlog(b))
{
return RedirectToAction("Index");
}
return RedirectToAction("ErrorPage");
} }
}
在BlogController 中涉及到的视图如下:
CreateBlog.cshtml
@{
ViewBag.Title = "CreateBlog";
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
//提交表单
function Submit() {
$("#frmRegist").submit();
}
//重置数据
function Reset() {
$("#frmReset").click(
function(){
$("#textTitle").val("");
$("#textContect").val("");
}
);
}
</script>
<h2>CreateBlog</h2>
<form id="frmRegist" method="post" action="CreateNewBlog">
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" class="form-control" placeholder="Title" name="Title" id="textTitle">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Contect</label>
<input type="text" class="form-control" placeholder="Contect" name="Contect" id="textContect">
</div>
<input type="reset" id="frmReset" value="reset" onclick="Reset()">
<input type="button" id="frmSubmit" value="Submit" onclick="Submit()">
</form>
ErrorPage.cshtml
@{
ViewBag.Title = "ErrorPage";
}
<h2>找不到页面</h2>
getEditBlog.cshtml
@{
ViewBag.Title = "getEditBlog";
}
<h2>编辑Blog</h2>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
function Submit() {
$("#frmSubmit1").submit();
}
</script>
<form id="frmSubmit1" method="post" action="seveBlog">
<div class="form-group">
<label>Id</label>
<input type="text" class="form-control" value="@Model.Id" name="Id">
</div>
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" value="@Model.Title" name="Title">
</div>
<div class="form-group">
<label>Contect</label>
<input type="text" class="form-control" value="@Model.Contect" name="Contect">
</div>
<div class="form-group">
<label>CreatedTime</label>
<input type="datetime" class="form-control" value="@Model.CreatedTime" name="CreatedTime">
</div>
<button type="reset" class="btn btn-default">Reset</button>
<input type="button" value="Submit" onclick="Submit()">
</form>
Index.cshtml
@using Core.Blogs;
<h2>Blog表单</h2>
<div style="width:100%; height:20px; ">
<span style="float:right;"><a href="Blog/CreateBlog">创建Blog</a></span>
</div> <!--用Requert 只能获取Get的参数-->
<form method="get" action="/Blog/Index">
<input type="text" name="key" value="@Request.QueryString["key"]" placeholder="查询" />
<input type="submit" value="查询" />
</form>
<table border="1" width="100%" cellpadding="0" cellspacing="10">
<tr>
<th>ID</th>
<th>Title</th>
<th>Contect</th>
<th>CreatedTime</th>
<th>操作</th>
</tr>
@foreach (Blog item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Title</td>
<td>@item.Contect</td>
<td>@item.CreatedTime</td>
<td><a href="Blog/getEditBlog?id=@item.Id">修改</a> | <a href="Blog/DeleteBlog?id=@item.Id">删除</a></td>
</tr>
} </table>
实现了你会发现,运行不起来,原因是你还需要添加 EntityFramework 程序集。
同时在查询的getBlog() 的时候,使用的 WhereIf 会报错,原因是EF中没有包含,所以我们自己写了一个类了对它进行泛化。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace System.Linq
{
public static class Extent
{
public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, System.Linq.Expressions.Expression<Func<T, bool>> predicate, bool condition)
{
return condition ? source.Where(predicate) : source;
}
public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, System.Linq.Expressions.Expression<Func<T, int, bool>> predicate, bool condition)
{
return condition ? source.Where(predicate) : source;
}
public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, Func<T, bool> predicate, bool condition)
{
return condition ? source.Where(predicate) : source;
}
public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, Func<T, int, bool> predicate, bool condition)
{
return condition ? source.Where(predicate) : source;
}
}
}
代码的位置在这里:

慢慢的你会发现很多的好东西,如 为什么要回填查询的Key?是怎么样实现?
MVC+EF 入门教程(三)的更多相关文章
- MVC+EF 入门教程(一)
一.前言 本人小白,写这篇博客是为了记录今天一天所学的知识,可能表达不是那么的准确和清楚,欢迎在留言区写下您的建议,欢迎纠错.希望这篇文章对你有所帮助学习 .Net MVC有所帮助.废话不多说了,我们 ...
- MVC+EF 入门教程(二)
一.前沿 为了使以后项目分开,所以我会添加3个类库.用于存储 实体.数据库迁移.服务.这种思路是源于我使用的一个框架 ABP.有兴趣的您,可以去研究和使用这个框架. 二.修改本地连接 在项目中,找到 ...
- mvc+ef入门(三)
(1)新建一个DAL层用来放置Accountcontext.cs和Accountinitializer.新建一个models层用来归放sysuser,sysrole和sysuserrole,三个类.( ...
- MVC+EF 入门教程(四)
一.前言 写了那么久,那么现在给大家看效果了 二.效果展示 点击创建Blog 显示 编辑 编辑成功,是不是很酷. 删除 终于完成了,准备睡觉!虽然有很多不足的地方,我会慢慢的去改的.感谢累了一天的自己 ...
- ASP.NET MVC 5 入门教程 (2) 控制器Controller
文章来源: Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc-5-get-started-controller.html 上一节:ASP.NET MVC ...
- ASP.NET MVC 5 入门教程 (4) View和ViewBag
文章来源: Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc-5-get-started-view.html 上一节:ASP.NET MVC 5 入门教 ...
- 无废话ExtJs 入门教程三[窗体:Window组件]
无废话ExtJs 入门教程三[窗体:Window组件] extjs技术交流,欢迎加群(201926085) 1.代码如下: 1 <!DOCTYPE html PUBLIC "-//W3 ...
- ASP.NET MVC 5 入门教程 (3) 路由route
文章来源: Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc-5-get-started-route.html 上一节:ASP.NET MVC 5 入门 ...
- ASP.NET MVC 5 入门教程 (1) 新建项目
文章来源: Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc-5-get-started-create-project.html 下一节:ASP.NET ...
随机推荐
- AIO5系统中-打印样式常见问题处理
1.为什么我的报表没有数据显示? 答:请看一下报表是否有绑定数据源,有添加查询,如果这些都做了,请看下主项数据的数据源有没有绑定,这些都绑定了,就会有数据的显示. 2.为什么我做的报表分组很乱? 答: ...
- 全内存的redis用习惯了?使用基于硬盘存储类似redis的nosql产品ssdb呢?
首先说一下背景,在双十一的时候,我们系统接受X宝的订单推送,同事原先的实现方式是使用redis的List作为推送数据的承载,在非大促的场景下, 一切运行正常,内存占用大概3-4G,机器是16G内存.由 ...
- 罗培羽—C语言简单游戏编程教学
编写许多软件都需要有菜单,那么如果我们使用tc之类的软件来编译程序的话,我们该怎么编写菜单呢?让我们一起来试试吧!第一步:简单例子 我们先来写个最简单的例子:#include<std ...
- 11-散列4 Hashing - Hard Version
题目 Sample Input: 11 33 1 13 12 34 38 27 22 32 -1 21 Sample Output: 1 13 12 21 33 34 38 27 22 32 基本思路 ...
- 【epub.js|翻译|原创】开源中间件epub.js的使用及其中文文档
epub是最流行的电子书规范之一,网络上对于Java Web有不少合适的方法来解析和呈现,但是关于epub.js的介绍比较少(尽管github上已经2K星了),更多的是概念性的内容,如: epub.j ...
- 【javaFX学习】(二) 控件手册
这里写的控件可能不是所有的控件,但是应该是比较齐全并足够用的了,后面还有图表类的,3d模型类,放在后面来写吧,太多了.javafx的功能比以前想象中的要强大.而且也很方便,所有的控件写完后再用Scen ...
- warning: C4819: 该文件包含不能在当前代码页(936)中表示的字符。请将该文件保存为 Unicode 格式以防止数据丢失
------问题-------------------- Qt项目使用 VC++ 编译器出现此错误. warning: C4819: 该文件包含不能在当前代码页(936)中表示的字符.请将该文件保存为 ...
- Python函数篇(2)-递归函数、匿名函数及高阶函数
1.全局变量和局部变量 一般定义在程序的最开始的变量称为函数变量,在子程序中定义的变量称为局部变量,可以简单的理解为,无缩进的为全局变量,有缩进的是局部变量,全局变量的作用域是整个程序,而局部变量的作 ...
- 随机生成N个字符(包含数字和字母)
'************************************************************* ' Name: GetRandomString ' Purpose: 随机 ...
- MySQL 性能优化的最佳20多条经验分享(一)(转)
当我们去设计数据库表结构,对操作数据库时(尤其是查表时的SQL语句),我们都需要注意数据操作的性能.这里,我们不会讲过多的SQL语句的优化,而只是针对MySQL这一Web应用最多的数据库.希望下面的这 ...