1. 程式人生 > 其它 >EF例題(簡易的增刪改查)(二)

EF例題(簡易的增刪改查)(二)

EF例題(簡易的增刪改查)(二)

今天也做了一套簡單的EF的增刪改查例題,今天還是簡單的說一個解題思路及方法:

效果如下:

Model層

今天的Model層是兩個表,將一個單選框作為一個表進行遍歷輸出

程式碼如下:

[Table("Advertising")]
public class Advertising
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
[ForeignKey("AdvertisingType")]
public int AID { get; set; }
public AdvertisingType AdvertisingType { get; set; }
public string ShuoMing { get; set; }
public int Num { get; set; }
public decimal Money { get; set; }
public int Width { get; set; }
public int Highly { get; set; }
public bool Mubiao { get; set; }
public DateTime ATime { get; set; }
}

DAL層

在DAl層新建項下的ADO.NET 實體資料模型選擇“空Code First模型”,然後對連線上下文的時候對在實體資料模型當中 新增 資料集屬性

然後更改web.config 資料庫連線字串

1.更改connectionString屬性名 data source 值 改成"."或資料庫例項名稱

2.更改connectionString屬性名 initial catalog 值 改成 自定義資料庫名稱

完成之後進行資料遷移,在啟動資料遷移的時候將預設建立的檔案的 AutomaticMigrationsEnabled 改為 true

完成之後新建Dal,對各項功能進行方法設立。

程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WeekLianXian.Models;

namespace WeekLianXian.DAL
{
    public class AdvertisingDal
    {

        AdvertisingDbCodtion DB = new AdvertisingDbCodtion();
        /// <summary>
        /// 顯示
        /// </summary>
/// <param name="totalcount"></param> /// <param name="totalpage"></param> /// <param name="Name"></param> /// <param name="pageindex"></param> /// <param name="pagesize"></param> /// <returns></returns> public List<Advertising> ShowList(out int totalcount,out int totalpage,int? AID,string Name,int pageindex=1,int pagesize=3) { IQueryable<Advertising> query = DB.Advertisings.Include("AdvertisingType"); if (!string.IsNullOrEmpty(Name)) { query = query.Where(a => a.Name.Contains(Name)); } if (AID != null) { query = query.Where(a => a.AID == AID); } totalcount = query.Count(); totalpage = Convert.ToInt32(Math.Ceiling(totalcount * 1.0 / pagesize)); return query.OrderBy(a => a.ID).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList(); } /// <summary> /// 新增 /// </summary> /// <param name="A"></param> /// <returns></returns> public int Add(Advertising A) { DB.Advertisings.Add(A); return DB.SaveChanges(); } /// <summary> /// 單刪 /// </summary> /// <param name="id"></param> /// <returns></returns> public int Del(int id) { var item = DB.Advertisings.Find(id); DB.Advertisings.Remove(item); return DB.SaveChanges(); } /// <summary> /// 批刪 /// </summary> /// <param name="ids"></param> /// <returns></returns> public int AllDel(string ids) { var id = ids.Split(','); foreach (var item in id) { DB.Advertisings.Remove(DB.Advertisings.Find(Convert.ToInt32(item))); } return DB.SaveChanges(); } /// <summary> /// 反填 /// </summary> /// <param name="id"></param> /// <returns></returns> public Advertising FindById(int id) { return DB.Advertisings.Find(id); } /// <summary> /// 修改 /// </summary> /// <param name="A"></param> /// <returns></returns> public int Edit(Advertising A) { DB.Entry(A).State = System.Data.Entity.EntityState.Modified; return DB.SaveChanges(); } public List<AdvertisingType> LoadType() { return DB.AdvertisingTypes.ToList(); } } }

控制器

在控制器的對DAL層中設立的方法進行呼叫,並新增對應的檢視

程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeekLianXian.DAL;
using PagedList;
using PagedList.Mvc;
using WeekLianXian.Models;

namespace WeekLianXian.Controllers
{
    public class AdvertisingController : Controller
    {
        AdvertisingDal dal = new AdvertisingDal();
        // GET: Advertising
        public ActionResult Index(int? AID, string Name, int pageindex = 1, int pagesize = 3)
        {
            ViewBag.Adtype = dal.LoadType();
            int totalcount;
            int totalpage;
            var list = dal.ShowList(out totalcount, out totalpage, AID, Name, pageindex, pagesize);
            var lilist = new StaticPagedList<Advertising>(list, pageindex, pagesize, totalcount);
            ViewBag.totalcount = totalcount;
            ViewBag.totalpage = totalpage;
            ViewBag.pageindex = pageindex;
            return View(lilist);
        }
        
        public ActionResult add()
        {
            ViewBag.Adtype = dal.LoadType();
            return View();
        }
        public ActionResult addList(Advertising A)
        {
            if (dal.Add(A) > 0)
            {
                return Content("<script>alert('新增成功');location.href='/Advertising/Index'</script>");
            }
            else
            {
                return Content("<script>alert('新增失敗');location.href='/Advertising/add'</script>");
            }
        }
        public ActionResult Del(string ids)
        {
            if (dal.AllDel(ids) > 0)
            {
                return Content("<script>alert('刪除成功');location.href='/Advertising/Index'</script>");
            }
            else
            {
                return Content("<script>alert('刪除失敗');location.href='/Advertising/Index'</script>");
            }
        }
        public ActionResult Findbyid(int id)
        {
            ViewBag.Adtype = dal.LoadType();
            return View(dal.FindById(id));
        }
        public ActionResult Edit(Advertising A)
        {
            if (dal.Edit(A) > 0)
            {
                return Content("<script>alert('修改成功');location.href='/Advertising/Index'</script>");
            }
            else
            {
                return Content("<script>alert('修改失敗');location.href='/Advertising/Findbyid'</script>");
            }
        }
    }
}

檢視

在今天的檢視中,小難點是使用按鈕進行全選反選,以及按鈕進行修改。

思路是點選按鈕,獲取所對應的複選框的ID,然後通過ID進行傳值

其餘程式碼如下:

顯示:

@using PagedList;
@using PagedList.Mvc;
@model StaticPagedList<WeekLianXian.Models.Advertising>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<form>
    
    <input id="cbkall" name="cbkall" type="button" value="全選" />
    <input id="Button1" type="button" value="新增" onclick="location.href='/Advertising/add'" />
    <input id="Button1" type="button" value="修改" onclick="Edit()" />
    <input id="Button1" type="button" value="刪除" onclick="Delete()" />
    <input id="Button1" name="ccball" type="button" value="不選" />
    <br />
    @Html.TextBox("Name", "", new { @placeholder = "名稱" })
    <input type="submit" value="查詢" class="btn btn-default" />
    <br />
    @foreach (var item in ViewBag.Adtype)
    {
        <a href="/Advertising/[email protected]">@item.AName</a>
    }
    <a href="/Advertising/Index">全部</a>
</form>
<table class="table table-bordered">
    <thead>
        <tr>
            <td>選擇</td>
            <td>廣告位名稱</td>
            <td>型別</td>
            <td>數量</td>
            <td>新增時間</td>
            <td>尺寸</td>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    <input id="cbk" name="cbk" type="checkbox" value="@item.ID" />
                </td>
                <td>@item.Name</td>
                <td>@item.AdvertisingType.AName</td>
                <td>@item.Num</td>
                <td>@item.ATime</td>
                <td>@item.Width*@item.Highly</td>
            </tr>
        }
    </tbody>
</table>
@Html.PagedListPager(Model, pageindex => Url.Action("Index", new
{
    Name = Request["Name"],
    pageindex,
    pagesize = 3
}), new PagedListRenderOptions
{
    LinkToPreviousPageFormat = "上一頁",
    LinkToNextPageFormat = "下一頁",
})
<span>總共有:@ViewBag.totalcount 條資料</span>
<span>總共有:@ViewBag.totalpage 頁</span>
<span>當前是第:@ViewBag.pageindex 頁</span>
<input id="txt" type="text" />
<input id="Button1" type="button" value="跳轉" onclick="Tiao()" />
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@section scripts{
    <script>
        var flag = true
        $("#cbkall").click(function () {
            $("[name=cbk]").prop("checked", flag);
            flag = !flag; 
        })
        function Delete() {
            var arr = [];
            $("[name=cbk]:checked").each(function () {
                arr.push(this.value);
            })
            if (arr.length === 0) {
                alert("請選擇要刪除的行");
                return;
            }
            if (confirm("確定刪除嗎?")) {
                location.href = "Del?ids=" + arr.toString();
            }
        }
        function Edit() {
            var arr = [];
            $("[name=cbk]:checked").each(function () {
                arr.push(this.value);
            })
            if (arr.length === 0) {
                alert("請選擇要刪除的行");
                return ;
            }
            if (arr.length > 1) {
                alert("不能選中多個位置");
                return;
            }
            if (arr.length === 1) {

            } location.href = "/Advertising/Findbyid?id=" + arr.toString();
           

        }
    </script>
}

  新增:

@model WeekLianXian.Models.Advertising
@{
    ViewBag.Title = "add";
}

<h2>add</h2>
<form action="addList" method="post">
    <table class="table table-responsive">
        <tr>
            <td>廣告位名稱</td>
            <td>
                @Html.TextBoxFor(a => a.Name)
            </td>
        </tr>
        <tr>
            <td>廣告型別</td>
            <td>
                @foreach (var item in ViewBag.Adtype)
                {
                    <input id="Radio1" name="AID" type="radio" value="@item.AID" />@item.AName
                }
            </td>
        </tr>
        <tr>
            <td>備註說明</td>
            <td>
                @Html.TextAreaFor(a => a.ShuoMing)
            </td>
        </tr>
        <tr>
            <td>顯示數量</td>
            <td>
                @Html.TextBoxFor(a => a.Num)
            </td>
        </tr>
        <tr>
            <td>價格</td>
            <td>
                @Html.TextBoxFor(a => a.Money)
            </td>
        </tr>
        <tr>
            <td>寬度</td>
            <td>
                @Html.TextBoxFor(a => a.Width)
            </td>
        </tr>
        <tr>
            <td>高度</td>
            <td>
                @Html.TextBoxFor(a => a.Highly)
            </td>
        </tr>
        <tr>
            <td>時間</td>
            <td>
                @Html.TextBoxFor(a => a.ATime)
            </td>
        </tr>
        <tr>
            <td>連線目標</td>
            <td>
                @Html.RadioButtonFor(a => a.Mubiao, true, new { @checked = "checked" })新視窗
                @Html.RadioButtonFor(a => a.Mubiao, false)原視窗
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input id="Button1" type="submit" value="儲存" />
            </td>
        </tr>
    </table>
</form>

  反填/修改

@model WeekLianXian.Models.Advertising

@{
    ViewBag.Title = "Findbyid";
}

<h2>Findbyid</h2>
<form action="Edit" method="post">
    @Html.HiddenFor(a=>a.ID)
    <table class="table table-responsive">
        <tr>
            <td>廣告位名稱</td>
            <td>
                @Html.TextBoxFor(a => a.Name)
            </td>
        </tr>
        <tr>
            <td>廣告型別</td>
            <td>
                @foreach (var item in ViewBag.Adtype)
                {
                    if (item.AID == Model.AID)
                    {
                        <input id="Radio1" name="AID" type="radio" value="@item.AID" checked  />@item.AName
                    }
                    else
                    {
                        <input id="Radio1" name="AID" type="radio" value="@item.AID" />@item.AName
                    }

                }
            </td>
        </tr>
        <tr>
            <td>備註說明</td>
            <td>
                @Html.TextAreaFor(a => a.ShuoMing)
            </td>
        </tr>
        <tr>
            <td>顯示數量</td>
            <td>
                @Html.TextBoxFor(a => a.Num)
            </td>
        </tr>
        <tr>
            <td>價格</td>
            <td>
                @Html.TextBoxFor(a => a.Money)
            </td>
        </tr>
        <tr>
            <td>寬度</td>
            <td>
                @Html.TextBoxFor(a => a.Width)
            </td>
        </tr>
        <tr>
            <td>高度</td>
            <td>
                @Html.TextBoxFor(a => a.Highly)
            </td>
        </tr>
        <tr>
            <td>時間</td>
            <td>
                @Html.TextBoxFor(a => a.ATime)
            </td>
        </tr>
        <tr>
            <td>連線目標</td>
            <td>
                @Html.RadioButtonFor(a => a.Mubiao, true, new { @checked = "checked" })新視窗
                @Html.RadioButtonFor(a => a.Mubiao, false)原視窗
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input id="Button1" type="submit" value="修改" />
            </td>
        </tr>
    </table>
</form>