【C#】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

 

第四,修改3个页面

1.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBlog.Models;
using System.Data;

namespace MVCBlog.Controllers
{
    public class HomeController : Controller
    {

        /// <summary>
        /// 数据上下文对象
        /// </summary>
        BlogDBEntities db = new BlogDBEntities();

            #region 查询新闻列表+ActionResult Index()
            /// <summary>
            /// 查询新闻列表
            /// </summary>
            /// <returns></returns>
            public ActionResult Index()
            {
                //1.查询数据库里的新闻数据(通过EF执行)
                //1.1第一种方法:使用SQO(标准查询运算符),查询所有新闻
                //db.news.Where(d =>d.id  !=0 );
                //List<Models.news> list = db.news.Where(d => d.id != 0).ToList ();

                //1.2第二种方法:使用linq语句,查询所有新闻标题
                //Linq仅仅是给程序员使用的语法糖,.net编译器会在编译时将linq转化为sqo
                List<Models.news> list = (from d in db.news where d.id != 0 select d).ToList();

                //2.将数据集合传给视图
                ViewData["datalist"] = list;

                //3.加载视图

                return View();
            }
            #endregion

            #region 执行删除操作(根据id)+ActionResult Del(int id)
            /// <summary>
            /// 执行删除操作(根据id)
            /// </summary>
            /// <param name="id">要删除的新闻id</param>
            /// <returns></returns>
            public ActionResult Del(int id)
            {
                try
                {
                    //1.创建要删除的对象
                    news modelDel = new news() { id = id };
                    //2.将对象添加到EF管理容器中
                    db.news.Attach(modelDel);
                    //3.将对象包装类的状态标识为删除状态
                    db.news.Remove(modelDel);
                    //4.更新到数据库
                    db.SaveChanges();
                    //5.更新成功,则令浏览器跳转到list方法
                    return RedirectToAction("Index", "Home");
                }
                catch (Exception ex)
                {
                    return Content("删除失败!" + ex.Message);
                }
            }
            #endregion

            #region 显示要修改的数据(根据id)+ActionResult Modify(int id)
            [HttpGet]
            /// <summary>
            /// 执行修改操作(根据id)
            /// </summary>
            /// <param name="id">要修改的新闻id</param>
            /// <returns></returns>
            public ActionResult Modify(int id)
            {
                try
                {
                    //根据id查询数据库,返回集合中,拿到第一个实体对象
                    news n = (from a in db.news where a.id == id select a).FirstOrDefault();
                    //生成分类下拉框列表集合List<SelectListItem> list
                    IEnumerable<SelectListItem> listitem = (from c in db.categories select c).ToList().Select(c => new SelectListItem { Value = c.id.ToString(), Text = c.name });
                    ViewBag.CateList = listitem;

                    //将n传递给视图显示 viewbag 或者viewdata

                    //加载视图,使用view的构造函数 将数据传给视图上的名为model的属性
                    return View(n);
                }
                catch (Exception ex)
                {
                    return Content("修改失败!" + ex.Message);
                }
            }
            #endregion

            #region 执行修改操作+ActionResult Modify(news model)
            [HttpPost]
            /// <summary>
            /// 执行修改操作
            /// </summary>
            /// <param name="model"></param>
            /// <returns></returns>
            public ActionResult Modify(news model)
            {
                try
                {
                    //将实体对象加入到EF对象容器中,并获取伪包装类对象
                    var entry = db.Entry<news>(model);
                    //将包装类对象的状态设置为unchanged
                    entry.State = System.Data.Entity.EntityState.Unchanged;
                    //设置需要提交的实体属性
                    entry.Property(a => a.title).IsModified = true;
                    entry.Property(a => a.content).IsModified = true;
                    //提交到数据库 完成修改
                    db.SaveChanges();
                    //5.更新成功,则令浏览器跳转到list方法
                    return RedirectToAction("Index", "Home");
                }
                catch (Exception ex)
                {
                    return Content("修改失败!" + ex.Message);
                }

            }
            #endregion

        }

  }

2.

<span style="font-size:18px;">
    @using MVCBlog.Models
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <style type="text/css">
        #tblist {
            border: 1px solid #0ff;
            width: 800px;
            margin: 10px auto;
            border-collapse: collapse;
        }

            #tblist th, td {
                border: 1px solid #0ff;
                padding: 10px;
            }
    </style>
    <script type="text/javascript">
        function Del(id) {
            alert("运行到了这里");
            if (confirm("您确定要删除吗?亲~~")) {
                window.location = "/Home/Del/" + id;
            }
        }
        function Modify(id) {
            window.location = "/Home/Modify/" + id;
        }

    </script>
</head>
<body>
    <table id="tblist">
        <tr>
            <th>id</th>
            <th>标题</th>
            <th>发布时间</th>
            <th>新闻分类</th>
            <th>操作</th>
        </tr>

        <!--遍历Action方法 设置给viewdata的数据集合,生成html代码-->
        @foreach (news n in ViewData["datalist"] as List<news>)
        {
            <tr>
                <td>@n.id </td>
                <td>@n.title </td>
                <td>@n.createTime </td>
                <td>@n.caid </td>
                <td>
                    <a href="javascript:Del(@n.id) ">删除</a>
                    <a href="javascript:Modify(@n.id )">修改</a>
                </td>
            </tr>
        }
    </table>
</body>
</html>
</span>

3.

<span style="font-size:18px;">
    @model MVCBlog.Models.news
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>修改</title>
    <style type="text/css">
        #tblist {
            border: 1px solid #0ff;
            width: 600px;
            margin: 10px auto;
            border-collapse: collapse;
        }

            #tblist th, td {
                border: 1px solid #0ff;
                padding: 10px;
            }
    </style>
</head>
<body>
    @using (Html.BeginForm("Modify", "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.title)</td>*@
                <!--使用htmlhelper的强类型方法直接从model中根据title属性生成文本框-->
                <td>@Html.TextBoxFor(a => a.title)</td>
            </tr>
            <tr>
                <td>分类:</td>
                <td>@Html.DropDownListFor(a => a.category, ViewBag.CateList as IEnumerable<SelectListItem>)</td>
            </tr>
            <tr>
                <td>内容:</td>
                <td>@Html.TextAreaFor(a => a.content, 10, 60, null)</td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="确定修改" />@Html.ActionLink("返回", "Index", "Home")</td>
            </tr>
        </table>
    }
</body>
</html>
</span>

第四,页面运行实现

猜你喜欢

转载自www.cnblogs.com/lixiaochong/p/9843661.html