公共增删改查(MVC+三层架构)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了公共增删改查(MVC+三层架构)相关的知识,希望对你有一定的参考价值。

1.建立数据访问层:新建一个项目,选择类库,命名为XXXDAL,然后把新生成的类删除,重新建一个类BaseDal,代码如下:

public class BaseDal<T> where T : class,new()
{

    syEntities1 db = new syEntities1();

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public int Add(T model)
    {
        db.Entry(model).State = EntityState.Added;
        return db.SaveChanges();
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public int Delete(T model)
    {
        db.Entry(model).State = EntityState.Deleted;
        return db.SaveChanges();
    }

    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public int Edit(T model)
    {
        db.Entry<T>(model).State = EntityState.Modified;
        return db.SaveChanges();
    }

    /// <summary>
    /// 查询
    /// </summary>
    /// <param name="whereLambda">lambda表达式</param>
    /// <returns></returns>
    public List<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
    {
        return db.Set<T>().Where<T>(whereLambda).ToList();
    }

    /// <summary>
    /// 查询并按指定列排序
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <param name="whereLambda"></param>
    /// <param name="orderbyLambda"></param>
    /// <returns></returns>
    public List<T> LoadEntities<K>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, K>> orderbyLambda)
    {
        return db.Set<T>().OrderBy<T, K>(orderbyLambda).Where<T>(whereLambda).ToList();
    }

    /// <summary>
    /// 查询分页
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <param name="pageIndex">第几页</param>
    /// <param name="pageSize">显示的行数量</param>
    /// <param name="whereLambda"></param>
    /// <param name="orderLambda"></param>
    /// <returns></returns>
    public List<T> LoadEntities<K>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, Expression<Func<T, K>> orderLambda)
    {
        return db.Set<T>().OrderBy<T, K>(orderLambda).Where<T>(whereLambda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize).ToList();
    }
}

2.建立业务逻辑层:新建一个项目,选择类库,命名为XXXBLL,然后把新生成的类删除,重新建一个类BaseBll,代码如下:

public abstract class BaseBll<T> where T : class,new()
{
    protected BaseDal<T> dal;

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public bool Add(T model)
    {
        return dal.Add(model) > 0;
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public bool Delete(T model)
    {
        return dal.Delete(model) > 0;
    }

    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public bool Edit(T model)
    {
        return dal.Edit(model) > 0;
    }

    /// <summary>
    /// 查询
    /// </summary>
    /// <param name="whereLambda"></param>
    /// <returns></returns>
    public List<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
    {
        return dal.LoadEntities(whereLambda);
    }

    /// <summary>
    /// 查询拼按指定列排序
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <param name="whereLambda"></param>
    /// <param name="orderbyLambda"></param>
    /// <returns></returns>
    public List<T> LoadEntities<K>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, K>> orderbyLambda)
    {
        return dal.LoadEntities(whereLambda, orderbyLambda);
    }

    /// <summary>
    /// 查询分页
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <param name="pageIndex">第几页</param>
    /// <param name="pageSize">显示的行数量</param>
    /// <param name="whereLambda"></param>
    /// <param name="orderLambda"></param>
    /// <returns></returns>
    public List<T> LoadEntities<K>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, Expression<Func<T, K>> orderLambda)
    {
        return dal.LoadEntities(pageIndex, pageSize, whereLambda, orderLambda);
    }
}

3.建立模型层:新建一个项目,从左边选择数据---ADO.NET实体数据模型,选择要连接的数据库,如下图:

技术分享

技术分享

4.如有新表Smno,那么只需要新建一个业务逻辑类和数据访问类:SmnoBll和SmnoDal,再继续父类BaseBll和BaseDal即可:

    public class SmnoBll : BaseBll<Smno>
    {
        public SmnoBll()
        {
            dal = new SmnoDal();//创建Smno这张表的实例
        }
    }
    public class SmnoDal : BaseDal<Smno>
    {

    }

5.控制器调用:

SmnoBll smnoBll = new SmnoBll();
public ActionResult Text()
{
    List<Smno> smno = smnoBll.LoadEntities(1, 10, u => true, u => u.Id);

    return View();
}

6.分页例子:

新建一个类PageNavHelper,代码如下:

public class PageNavHelper
{
    //主要就是输出分页的超级链接的标签
    //自定义分页Helper扩展
    public static string ShowPageNavigate(int currentPage, int pageSize, int totalCount)
    {
        var redirectTo = HttpContext.Current.Request.Url.AbsolutePath;
        pageSize = pageSize <= 0 ? 3 : pageSize;
        var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数
        var output = new StringBuilder();
        //output.AppendFormat("<table border=‘1‘ style=‘width:330px;height:10px‘><tr><td>");
        if (totalPages > 1)
        {
            //if (currentPage != 1)
            //处理首页连接
            {
                output.AppendFormat("<a class=‘pageLink‘ href=‘{0}?pageIndex=1&pageSize={1}‘>首页</a> ", redirectTo, pageSize);
            }
            if (currentPage > 1)
            {//处理上一页的连接
                output.AppendFormat("<a class=‘pageLink‘ href=‘{0}?pageIndex={1}&pageSize={2}‘>上一页</a> ", redirectTo, currentPage - 1, pageSize);
            }
            else
            {
                // output.Append("<span class=‘pageLink‘>上一页</span>");
            }

            output.Append(" ");
            int currint = 5;
            for (int i = 0; i <= 10; i++)
            {//一共最多显示10个页码,前面5个,后面5个
                if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
                {
                    if (currint == i)
                    {//当前页处理
                        //output.Append(string.Format("[{0}]", currentPage));
                        output.AppendFormat("<a class=‘cpb‘ href=‘{0}?pageIndex={1}&pageSize={2}‘>{3}</a> ", redirectTo, currentPage, pageSize, currentPage);
                    }
                    else
                    {//一般页处理
                        output.AppendFormat("<a class=‘pageLink‘ href=‘{0}?pageIndex={1}&pageSize={2}‘>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint);
                    }
                }
                output.Append(" ");
            }
            if (currentPage < totalPages)
            {//处理下一页的链接
                output.AppendFormat("<a class=‘pageLink‘ href=‘{0}?pageIndex={1}&pageSize={2}‘>下一页</a> ", redirectTo, currentPage + 1, pageSize);
            }
            else
            {
                //output.Append("<span class=‘pageLink‘>下一页</span>");
            }
            output.Append(" ");
            if (currentPage != totalPages)
            {
                output.AppendFormat("<a class=‘pageLink‘ href=‘{0}?pageIndex={1}&pageSize={2}‘>末页</a> ", redirectTo, totalPages, pageSize);
            }
            output.Append(" ");
        }
        output.AppendFormat("第{0}页 / 共{1}页", currentPage, totalPages);//这个统计加不加都行
        //output.AppendFormat("</td></tr></table>");
        return output.ToString();
    }
}

新建一个控制器Home并为Index添加一个视图:

public ActionResult Index()
{
    return View();
}

视图html代码(含css、jquery):

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>loadjson</title>
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.8.20.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <style type="text/css">
        body {
        }

        .paginator {
            font: 12px Arial, Helvetica, sans-serif;
            padding: 10px 20px 10px 0;
            margin: 0px;
        }

            .paginator a {
                border: solid 1px #ccc;
                color: #0063dc;
                cursor: pointer;
                text-decoration: none;
            }

                .paginator a:visited {
                    padding: 1px 6px;
                    border: solid 1px #ddd;
                    background: #fff;
                    text-decoration: none;
                }

            .paginator .cpb {
                border: 1px solid #F50;
                font-weight: 700;
                color: #F50;
                background-color: #ffeee5;
            }

            .paginator a:hover {
                border: solid 1px #F50;
                color: #f60;
                text-decoration: none;
            }

            .paginator a, .paginator a:visited, .paginator .cpb, .paginator a:hover {
                float: left;
                height: 16px;
                line-height: 16px;
                min-width: 10px;
                _width: 10px;
                margin-right: 5px;
                text-align: center;
                white-space: nowrap;
                font-size: 12px;
                font-family: Arial,SimSun;
                padding: 0 3px;
            }
    </style>
    <script type="text/javascript">
        $(function () {
            //页面加载完成后从后如加载当前页数据
            initTable();
        });

        //初始化表格数据
        function initTable(queryData) {
            $.getJSON("/Home/loadjson/", queryData, function (data) {
                var tb = $("#tbList");
                //先移除旧的,添加新的
                $("#tbList tr[type=data]").remove();
                for (var i = 0; i < data.Data.length; i++) {
                    var strTr = "<tr type=‘data‘>";
                    strTr += "<td>" + data.Data[i].Id + "</td>";
                    strTr += "<td>" + data.Data[i].Pn + "</td>";
                    strTr += "<td>" + data.Data[i].Unit + "</td>";
                    strTr += "<td>" + data.Data[i].PnName + "</td>";
                    strTr += "<td><a UId=‘" + data.Data[i].id + "‘ href=‘javascript:void(0)‘>修改</a>" +
                        "<a UId=‘" + data.Data[i].ID + "‘ href=‘javascript:void(0)‘>删除</a></td>";
                    strTr += "</tr>";
                    tb.append(strTr);
                }
                $("#Nav").html(data.NavStr);

                //绑定分页标签的点击事件
                $(".pageLink").click(function () {
                    //把页码弹出来
                    var strHref = $(this).attr("href");
                    var queryStr = strHref.substr(strHref.indexOf(?) + 1);
                    initTable(queryStr);
                    return false;
                });
            });
        }
        
    </script>
</head>
<body>
    <div>
        <table border="1" id="tbList">
            <tr>
                <td>id</td>
                <td>型号</td>
                <td>单位</td>
                <td>名字</td>
                <td>修改与删除</td>
            </tr>
        </table>

        <div id="Nav" class="paginator">
        </div>

    </div>
</body>
</html>

在Home控制器下添加一个方法loadjson:

        /// <summary>
        /// 异步分页
        /// </summary>
        /// <returns></returns>
        public ActionResult loadjson()
        {
            int pageSize = Request["pageSize"] == null ? 10 : int.Parse(Request["pageSize"]);
            int pageIndex = Request["pageIndex"] == null ? 1 : int.Parse(Request["pageIndex"]);
            int totalCount = smnoBll.LoadEntities(u => true).Count;

            //给前台userinfo所有的数据,并且是json格式
            //var allorder = smnoBll.tbl_admin.OrderBy(u => u.id)
            //    .Skip(pageSize * (pageIndex - 1))
            //    .Take(pageSize)
            //    .ToList();
            var allorder = smnoBll.LoadEntities(pageIndex, pageSize, u => true, u => u.Id);
            //接受一个对像,内部把此对象使用javaScript序列化类对象志字符串,发送到前台

            var data = from u in allorder select new { u.Id, u.Pn, u.Unit, u.PnName };

            string strNav = PageNavHelper.ShowPageNavigate(pageIndex, pageSize, totalCount);

            var result = new { Data = data, NavStr = strNav };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

效果如下图:

技术分享

以上是关于公共增删改查(MVC+三层架构)的主要内容,如果未能解决你的问题,请参考以下文章

JavaWeb::理解MVC模式和三层架构,完成数据的增删改查

asp.net mvc oracle 做的增删改查功能,给我份源码。

怎么创建SpringBoot项目并实现数据库的增删改查

MVC三层架构

MVC三层架构

MVC三层架构