MVC+EF+Linq 实例
天才第一步:创建数据库
创建数据库的代码:
create table category(
id int primary key,
name nvarchar(20)
)
create table news(
id int primary key,
title nvarchar(20),
content nvarchar(200),
createTime datetime ,
caid int constraint fk_ca_id foreign key references category(id)
)
create table comment(
id int primary key,
content nvarchar(100),
createTime dateTime,
userIp nvarchar(50),
newsId int constraint fk_news_id foreign key references news(id)
)
手动添加一些数据
天才第二步:创建MVC工程文件
天才第三步:在Models文件夹下创建EF
“来自数据库的EF设计器” ,下一步
选择数据库,如果服务器用的是本地(.),下面就选择Windows身份验证,然后找到自己的数据库
下面的”另存为“的名称默认就好
勾选自己需要的表
这就是创建好EF的样子偶~~~
天才第四步:编码–修改三个页面
一、首先是控制器(HomeCotroller)名字是默认生成的,也可以自己修改!
HomeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_YZY.Models;
using System.Data.Entity.Infrastructure;
namespace MVC_YZY.Controllers
{
//1、控制器类(继承了controller)
public class HomeController : Controller
{
/// <summary>
/// 数据上下文对象
/// </summary>
newssystemEntities db = new newssystemEntities();
#region 1、 查询 文章 列表 +ActionResult Index()
/// <summary>
/// 查询 文章 列表
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
//1.查询 数据库里的 文章数据(通过 EF 执行)
//1.1第一种方式:使用 SQO(标准查询运算符) 查询所有未软删除的文章
//实际返回的是 一个 IQueryable 对象?此处其实是返回了一个 IQueryable 接口的子类对象
//IQueryable<newssystemEntities> query= db.news.Where(d => d.AIsDel == false);
//此时真实返回的类型未 DbQuery<T> 支持 延迟加载!只有当使用道数据的时候,才去 查询数据库
//DbQuery<newssystemEntities> query = (db.news.Where(d => d.AIsDel == false)) as DbQuery<newssystemEntities>;
//直接将 返回的 DbQuery 转成 List<T>集合,也就是立即查询数据库,并返回查询到的集合
//List<news> list = db.news.Where(d => d.caId == 0).ToList();
//1.2第二种方式:使用 Linq语句 查询所有新闻标题
//Linq 仅仅是给程序员用的 语法糖,.NET编译器会再编译程序集(中间代码)的时候,将linq语句转成 SQO(标准查询运算符)
List<news> list = (from d in db.news where d.caId != 0 select d).ToList();
//2.将集合数据传给视图
//ViewBag.DataList = list;
ViewData["DataList"] = list;
//3."加载" 视图
return View();
}
#endregion
#region 2、 执行删除操作(根据ID)+ActionResult Del(int id)
/// <summary>
/// 执行删除操作(根据ID)
/// </summary>
/// <param name="id">要删除的新闻ID -/home/del/12</param>
/// <returns></returns>
public ActionResult Del(int id)//此ID会根据路由的url 配置{id}占位符,而被 12 替换掉
{
//先查询出来再删除
var modelDel = db.news.FirstOrDefault(n => n.id == id);
db.news.Remove(modelDel);
int res= db.SaveChanges();
return RedirectToAction("Index", "Home");
}
#endregion
#region 3、 显示要修改的数据 +ActionResult Modify(int id)
[HttpGet]
/// <summary>
/// 0.4 显示要修改的数据
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Modify(int id)
{
#region 本步骤的思路
//1、获取选中的新闻 显示到一个新的页面。
/*
*
* 首先 根据newsid获取该新闻的信息
* 将新闻的标题和内容显示再文本框中
*
* 然后查询所有的新闻分类,显示在下拉框中
*
* 最后根据该新闻的类别 设置为下拉框的默认选中
*/
//news n = (from a in db.news where a.caId==0 select a).FirstOrDefault();
//IEnumerable<SelectListItem> m = (from c in db.categories select c).ToList().Select(c => new SelectListItem { Value = c.id.ToString(), Text = c.name });
#endregion
news n = db.news.Find(id);
ViewBag.newTitle = n.title;
ViewBag.newContent = n.content;
var categories = from c in db.categories select c;
var temp = new SelectList(categories, "id", "name",n.caId);
ViewBag.categories = temp;
return View();
}
#endregion
#region 执行修改 +ActionResult Modify(news news)
[HttpPost]
/// <summary>
/// 执行修改
/// </summary>
/// <param name="news"></param>
/// <returns></returns>
public ActionResult Modify2()
{
//首先,找到对象
int newid =Convert.ToInt32( Request.Form["id"]);
var n = db.news.FirstOrDefault(m => m.id == newid);
//var n = db.news.Find(id);
//然后,更新数据对象
n.caId =Convert.ToInt32( Request.Form["dropCate"]);
n.content = Request.Form["txtContent"];
n.title = Request.Form["newTitle"];
//最后,保存修改
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
#endregion
}
}
二、然后是Index.cshtml页面
@using MVC_YZY.Models
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
#tbList {
border: 1px solid #0094ff;
width: 800px;
margin: 10px auto;
border-collapse: collapse;
text-align: center
}
#tbList th, td {
border: 1px solid #0094ff;
padding: 10px;
text-align: center
}
</style>
<script type="text/javascript">
function Del(id) {
if (confirm("您确认要删除么?")) {
window.location = "/Home/Del/" + id;
}
}
function Modify(id) {
window.location = "/Home/Modify/" + id;
}
</script>
</head>
<body>
<div>
<table id="tbList">
<tr>
<th>ID</th>
<th>标题</th>
<th>内容</th>
<th>发布时间</th>
<th>CaId</th>
<th>操作</th>
</tr>
<!--遍历 action方法 设置给 ViewData 的集合数据,生成HTML 代码-->
@foreach (news a in ViewData["DataList"] as List<news>)
{
<tr>
<td>@a.id</td>
<td>@a.title</td>
<td>@a.content</td>
<td>@a.createTime</td>
<td>@a.caId</td>
<td>
<a href="javascript:Del( @a.id)">删除</a>
<a href="javascript:Modify(@a.id)">修改</a>
</td>
</tr>
}
</table>
</div>
</body>
</html>
三、最后是 Modify.cshtml 页面
@model MVC_YZY.Models.news
<!--指定页面Model的属性 类型-->
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>修改</title>
<style type="text/css">
#tbList {
border: 1px solid #0094ff;
width: 400px;
margin: 10px auto;
border-collapse: collapse;
}
#tbList th, td {
border: 1px solid #0094ff;
padding: 10px;
}
</style>
</head>
<body>
@using (Html.BeginForm("Modify2", "Home", FormMethod.Post))
{
<table id="tbList">
<tr>
<td colspan="2">修改 @Html.HiddenFor(a => a.id)</td>
</tr>
<tr>
<td>标题:</td>
@*<td>@Html.TextBox("txtName", (object)Model.ATitle)</td>*@
<!--使用HTMLHelper强类型方法 直接 从MOdel 中根据title属性生成文本框-->
<td>@Html.TextBox("newTitle", ViewBag.newTitle as string)</td>
</tr>
<tr>
<td>分类:</td>
<!--使用强类型方法根据 标题 属性生成下拉框 并自动根据model属性里的title 设置下拉框的 默认选中项-->
@*<td>@Html.DropDownListFor(a=>a.id, ViewBag.CateList as IEnumerable<SelectListItem>)</td>*@
<td>@Html.DropDownList("dropCate",ViewBag.categories as SelectList) </td>
</tr>
<tr>
<td>内容:</td>
<!--使用HTMLHelper强类型方法 直接 从MOdel 中根据content属性生成文本域-->
@*<td>@Html.TextAreaFor(a => a.content, 10, 60, null)</td>*@
<td>@Html.TextBox("txtContent", ViewBag.newContent as string)</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="确定修改" />@Html.ActionLink("返回", "Index", "Home")</td>
</tr>
</table>
}
</body>
</html>
天才第五步:查看运行效果
一、删除页面
二、修改页面