欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# 使用EF框架实现增删改查

程序员文章站 2024-01-18 22:27:58
...

C# 使用EF框架实现增删改查

一:创建项目和单键三层就不说了:
二:页面显示列表

@{
    Layout = "~/Views/MasterEdition.cshtml";
    ViewBag.Title = "Brand";
 
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>品牌管理</title>
</head>
<body>
    <div class="margin" id="page_style">
        <div class="operation clearfix mb15 same_module">
            <ul class="choice_search">
                <li class="clearfix col-xs-2 col-lg-3 col-ms-3 ">
                    <label class="label_name ">品牌名称:</label>
                    <input placeholder="输入品牌名称" id="brandname" type="text" class="form-control col-xs-8 col-lg-8 col-ms-8" />
                </li>
                <li class="clearfix col-xs-2 col-lg-3 col-ms-3">
                    <label class="label_name ">添加时间:</label>
                    <input class="inline laydate-icon form-control Select_Date" id="start" />
                </li>
                <li class="clearfix col-xs-2 col-lg-3 col-ms-3 ">
                    <button type="button" class="btn button_btn bg-deep-blue " οnclick="TableReload()" ><i class="icon-search"></i>查询</button>
                </li>
                @*<li class="clearfix col-xs-2 col-lg-3 col-ms-3 ">
                    Brand:@Session["name"]
                    @HttpContext.Current.Application["count"]
                </li>*@
            </ul>
        </div>
 
        <!--品牌列表-->
        <div class="list_Exhibition list_show padding15">
            <div class="operation clearfix mb15  same_module">
                <span class="l_f">
                    <a href="/Brand/Add_Brand" title="添加品牌" class="btn button_btn bg-deep-blue"><i class="fa fa-plus"></i>添加品牌</a>
                    <a href="javascript:ovid()"  id="deleteBrand"  οnclick="Deletes()" data-type="getCheckData" class="btn  button_btn btn-danger"><i class="fa fa-trash"></i>批量删除</a>
                </span>
               @* <span class="r_f">共:<b>11</b>个品牌</span>*@
            </div>
            <table id="BrandTable" class="layui-hide" lay-filter="test"></table>
        </div>
    </div>
</body>
</html>
<script type="text/html" id="display">
    <input type="checkbox" name="switch" value="{{d.Id}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="Status" {{ d.Status == 1 ? 'checked' : '' }} />
</script>
<script type="text/html" id="barDemo">
    <a title="编辑"  href="javascript:;" lay-event="edit" class="btn btn-xs btn-info">编辑</a>
    <a title="删除" href="javascript:;"   lay-event="del" class="btn btn-xs btn-delete">删除</a>
</script>
<script>
layui.use('table', function () {
        var table = layui.table,
            form = layui.form;
        //第一个实例
        table.render({
            elem: "#BrandTable",
            height: 400,
            url: '/Brand/BrandQueryTable',
            page: true,
            cols: [[ //表头
              { type: 'checkbox', fixed: 'left', align: 'center' }
            , { field: 'Id', align: 'center', title: 'Id', sort: true }
            , { field: 'Name', align: 'center', title: '品牌名称', sort: true }
            , { field: 'Logo',height:60, align: 'center', title: '品牌logo', sort: true, templet: '<div οnclick="show_img(this)" ><img  width="40" height="40" src="{{d.Logo}}"></div>' }
            , { field: 'OrderBy', align: 'center', title: '排序', sort: true }
            , { field: 'UpdateTime', align: 'center', title: '修改时间', sort: true, templet: "<div>{{Format(d.UpdateTime,'yyyy-MM-dd hh:mm:ss')}}</div>" }
            , { field: 'Status', align: 'center', title: '状态', sort: true ,toolbar:"#display" }
            , { field: 'cz',fixed: 'right' ,title: '操作', align: 'center', toolbar: '#barDemo', width: 150, sort: true }
             ]]
        })
 
         //监听工具条
    table.on('tool(test)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {//删除
            layer.confirm('真的删除行么', function (index) {
                $.ajax({
                    type: "post",
                    url: "/Brand/BrandDeleteId?id=" + data.Id,
                    async: false,
                    success: function (data) {
                        if (data.Success) {
                            layer.msg("删除成功", { time: 2000 }, function () {
                                obj.del();
                               layer.close(index);
                            })
                        }
                    }
                })
            });
        } else if (obj.event === 'edit') {//修改
            location.href = "/Brand/Add_Brand?id=" + data.Id;
        }
    });
 
     //是否启用switch(Status)对应lay-filter="Status"
    form.on('switch(Status)', function (obj) {
        var data = {};
        data.Id = this.value;
        data.Status = 0;
        if (obj.elem.checked) {
            data.Status=1
        }
        $.ajax({
            type: "post",
            url: "/Brand/BrandUpdateStatus",
            data: data,
            success: function (data) {
                if (data.Success) {
                    //  location.reload();
                    layer.msg("修改成功!!", {
                        time: 2000 //1秒关闭(如果不配置,默认是3秒)
                    });
                } else {
                    layer.msg("修改失败", { icon: 5, time: 200 });
                }
            }
        })
    });
 
});
 
    //批量删除
    function Deletes() {
        var table = layui.table;
        //获取选中数据
        var checkStatus = table.checkStatus('BrandTable')
            , data = checkStatus.data;
        //获取拼接的id
        var id = BatchDelete(data);
        //删除数据
        layer.confirm('真的要删除吗', function (index) {
            $.ajax({
                url: "/Brand/DeleteBrand?brand=" + data,
                type: "Post",
                success: function (data) {
                    if (data.Success) {
                        layer.msg('删除成功!', {
                            title: '提示框',
                            icon: 1,
                            time: 2000
                        }, function () {
                            TableReload();
                            layer.close(index);
                        });
                    }
                    else {
                        layer.msg('删除失败!', {
                            title: '提示框',
                            icon: 1,
                            time: 2000
                        });
                    }
                }
            });
        })
    }
 
    //拼接id
    function BatchDelete(data) {
        var id = "";
        for (var i = 0; i < data.length; i++) {
            if (i != data.length - 1) {
                id += data[i].Id + ',';
            }
            else {
                id += data[i].Id;
            }
        }
        return id;
    }
 
 
   //列表刷新
    function TableReload() {
        var table = layui.table;
        var name = $('#brandname').val();
        var addTime = $('#start').val();
        table.reload('BrandTable', {
            where: {
                'name': name,
                'datetime': addTime
            }
        });
    }
 
</script>
<script>
    //设置内页框架布局
    $(function () {
        $("#Sellerber").frame({
            float: 'left',
            color_btn: '.skin_select',
            Sellerber_menu: '.list_content',
            page_content: '.list_show',//内容
            datalist: ".datatable_height",//数据列表高度取值
            header: 65,//顶部高度
            mwidth: 350,//宽度自定义
            minStatue: true,
 
        });
    });
    //设置时间
    laydate({
        elem: '#start',
        event: 'focus'
    });
</script>
<script type="text/javascript">
                //require.config({
                //    paths: {
                //        echarts: './js/dist'
                //    }
                //});
                //require(
                //    [
                //        'echarts',
                //        'echarts/chart/pie',   // 按需加载所需图表,如需动态类型切换功能,别忘了同时加载相应图表
                //        'echarts/chart/funnel'
                //    ],
 
                //);
</script>

效果:

三:后台代码

C# 使用EF框架实现增删改查

/// <summary>
        /// 显示品牌数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public JsonResult BrandQueryTable(int page ,int limit,string name,string datetime)
        {
            int count = 0;
            
            List<Brand> list = new List<Brand>();
            if (!string.IsNullOrEmpty(name)&& !string.IsNullOrEmpty(datetime))
            {
                DateTime date = DateTime.Parse(datetime);
                list = brandService.QueryPageList(page, limit, b => b.Name.Contains(name)&&b.UpdateTime<= date, b=>b.OrderBy, out count);
            }else if (!string.IsNullOrEmpty(datetime))
            {
                DateTime date = DateTime.Parse(datetime);
                list = brandService.QueryPageList(page, limit, b=> b.UpdateTime <= date, b => b.OrderBy, out count);
            }else if (!string.IsNullOrEmpty(name))
            {
                list = brandService.QueryPageList(page, limit, b => b.Name.Contains(name), b => b.OrderBy, out count);
            }
            else
            {
                list= brandService.QueryPageList(page, limit, b => b.Id != 0, b => b.OrderBy, out count);
            }
            PageListResult<Brand> plr = new PageListResult<Brand>();
            plr.code = 0;
            plr.msg = "";
            plr.data = list;
            plr.count = count;
 
            return Json(plr, JsonRequestBehavior.AllowGet);
        }

三:新增或修改操作页面代码:

@using MY.ShoppingBackstage.Model;
@{
    Layout = "~/Views/MasterEdition.cshtml";
    var brand = ViewBag.Brand as Brand;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <script src="~/js/jquery.dataTables.min.js"></script>
    <script src="~/js/jquery.dataTables.bootstrap.js"></script>
    <script src="~/js/hsCheckData.js" type="text/javascript"></script>
    <title>添加分类</title>
</head>
<body>
    <div class="margin inside_pages clearfix">
        <div class="add_style clearfix relative">
            <ul class="add_conent">
                <li class=" clearfix">
                    <label class="label_name">
                        <i>*</i>品牌名称:
                    </label>
                    <input name="" type="hidden" class="add_text form-control" id="BrandId" value="@brand.Id" />
                    <input name="" type="text" class="add_text form-control" id="BrandName" value="@brand.Name" />
                </li>
                <li class=" clearfix">
                    <label class="label_name"><i>*</i>品牌序号:</label>
                    @{
                        var orderby = "";
                        if (brand.OrderBy != 0)
                        {
                            orderby = brand.OrderBy.ToString();
                        }
                    }
                    <input name="" type="text" id="OrderBy" value="@orderby" class="add_text form-control" style="width:80px" />
                </li>
                <li class=" clearfix">
                    <label class="label_name">品牌图片:</label>
                    <div class="layui-upload">
                        <button type="button" class="layui-btn" id="test1">上传图片</button>
                        <div class="layui-upload-list">
                            <img class="layui-upload-img" id="demo1" src="@brand.Logo" />
                            <p id="demoText"></p>
                        </div>
                    </div>
                </li>
 
                <li class=" clearfix"><label class="label_name">品牌描述:</label> <textarea name="" id="Description" cols="50" rows="300" class="textarea" οnkeyup="checkLength(this);">@brand.Description</textarea><span class="wordage">剩余字数:<span id="sy" style="color:Red;">500</span>字</span></li>
 
            </ul>
            <div class="Button_operation btn_width">
                <button class="btn button_btn bg-deep-blue" onClick="article_save_submit()" type="button">保存</button>
                <button class="btn button_btn bg-gray" type="button">取消</button>
            </div>
        </div>
    </div>
</body>
</html>
<script>
 
    layui.use('upload', function () {
        var $ = layui.jquery
            , upload = layui.upload;
        var id = 0;
        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            , url: '/FileUpload/UploadImage'
            , done: function (res) {
                //如果上传失败
                if (res.Success) {
                    $('#demo1').attr('src', res.Url); //图片链接(base64)
                    $('#demo1').attr('width', 80);
                    $('#demo1').attr('height', 80);
                } else {
                    layer.msg(res.info, function () { })
                }
                //上传成功
            }
            , error: function () {
                layer.msg("上传异常");
            }
        });
 
    });
    //表单提交
    function article_save_submit() {
        var data = {};
        data.Id = $("#BrandId").val();
        data.Name = $("#BrandName").val();
        data.Logo = $("#demo1").attr('src');
        data.Description = $("#Description").val();//描述
        data.OrderBy = $("#OrderBy").val();//排序
        $.ajax({
            type: "post",
            url: "/Brand/BrandAddORUpdate",
            data: data,
            success: function (result) {
                layer.msg(result.Info, { icon: 1, time: 2000, shade: 0.2 }, function () {
                    if (result.Success) {
                        location.href = "/Brand/Brand_Manage";
                    }
                });
            }
        })
    }
</script>
<script>
     function checkLength(which) {
        var maxChars = 500;
        if (which.value.length > maxChars) {
            layer.open({
                icon: 2,
                title: '提示框',
                content: '您出入的字数超多限制!',
            });
            // 超过限制的字数了就将 文本框中的内容按规定的字数 截取
            which.value = which.value.substring(0, maxChars);
            return false;
        } else {
            var curr = maxChars - which.value.length; // 减去 当前输入的
            document.getElementById("sy").innerHTML = curr.toString();
            return true;
        }
    }
    $(function () {
        var ue = UE.getEditor('editor');
    });
    $(document).ready(function () {
        var spotMax = 8;
        if ($('div.images_Upload').size() >= spotMax) { $(obj).hide(); }
        $("#add_Upload").on('click', function () {
            var cid = $('.images_Upload').each(function (i) { $(this).attr('id', "Uimages_Upload_" + i) });
            addSpot(this, spotMax, cid);
        });
    });
    laydate(start);
    laydate(end);
    /*********滚动事件*********/
    $("body").niceScroll({
        cursorcolor: "#888888",
        cursoropacitymax: 1,
        touchbehavior: false,
        cursorwidth: "5px",
        cursorborder: "0",
        cursorborderradius: "5px"
    });
</script>

效果:
C# 使用EF框架实现增删改查后台代码:

/// <summary>
        /// 添加或修改品牌
        /// </summary>
        /// <param name="brand"></param>
        /// <returns></returns>
        public JsonResult BrandAddORUpdate(Brand brand)
        {
            brand.UpdateTime = DateTime.Now;
            brand.Status = 1;
            if (brand.Id == 0)
            {
                //添加
                operate.Success = brandService.Add(brand);
                operate.Info = operate.Success ? "添加成功" : "添加失败";
            }
            else
            {
                //修改
                operate.Success = brandService.Update(brand);
                operate.Info = operate.Success ? "修改成功" : "修改失败";
            }
            return Json(operate);
        }

删除:

/// <summary>
        /// 根据id删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public  JsonResult BrandDeleteId(int id)
        {
            operate.Success = brandService.Delete(id);
            return Json(operate);
        }