zoukankan      html  css  js  c++  java
  • 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="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?是怎么样实现?

      

  • 相关阅读:
    python学习总结
    内存池设计与实现
    RFC太网接口类型定义
    linux下查看网卡速率
    linux 下的clock_gettime() 获取时间函数
    添加linux系统调用的两种方式
    内核态与用户态通信 之 sockopt
    linux进程间通信方式
    linux进程间通信同步-共享内存
    Linux忘记密码常用的几种解决方法
  • 原文地址:https://www.cnblogs.com/gzbit-zxx/p/7342481.html
Copyright © 2011-2022 走看看