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

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

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

今天簡單的做了一套EF的增刪改查例題,下面簡單的說一下解題思路及方法,然後在說一下一些對於我來說比較困難的點。

效果如下

Model層

在model層建立四個表,主表為使用者表,一個下拉框為一個表進行四表聯查

分別設立四個表的主鍵,並在主表中設立外來鍵於其餘四個表進行關聯

程式碼如下:

namespace MoNiYueKao.Models
{
[Table("Users")]
public class Users
{
[Key]
public int UID { get; set; }
public string Zhao { get; set; }
[ForeignKey("UserType")]
public int TID { get; set; }
public UserType UserType { get; set; }
[ForeignKey("UserBu")]
public int BID { get; set; }
public UserBu UserBu { get; set; }
public string Name { get; set; }
[ForeignKey("UserChen")]
public int CID { get; set; }
public UserChen UserChen { get; set; }
public bool JIzhao { get; set; }
public decimal MaxMoney { get; set; }
public decimal MinMoney { get; set; }
public DateTime CTime { get; set; }
public string Xinxi { get; set; }
}
}

DAL層

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

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

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

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

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

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

程式碼如下:

 public class UsersDal
{
UsersDbContext Db = new UsersDbContext();
public List<UserBu> LoadBuMen()
{
return Db.UserBus.ToList();
}
public List<UserChen> LoadChen()
{
return Db.UserChens.ToList();
}
public List<UserType> LoadType()
{
return Db.UserTypes.ToList();
}
/// <summary>
/// 顯示
/// </summary>
/// <param name="totalcount"></param>
/// <param name="totalpage"></param>
/// <param name="TID"></param>
/// <param name="BID"></param>
/// <param name="pageindex"></param>
/// <param name="pagesize"></param>
/// <returns></returns>
public List<Users>ShowList(out int totalcount, out int totalpage,int? TID,int? BID,int pageindex=1,int pagesize=3)
{
IQueryable<Users> query = Db.Userss.Include("UserType").Include("UserBu").Include("UserChen");
if (TID != null)
{
query = query.Where(a => a.TID == TID);
}
if (BID != null)
{
query = query.Where(a => a.BID == BID);
}
totalcount = query.Count();//總條數
totalpage = Convert.ToInt32(Math.Ceiling(totalcount * 1.0 / pagesize));
return query.OrderBy(a => a.UID).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
}
/// <summary>
/// 新增
/// </summary>
/// <param name="A"></param>
/// <returns></returns>
public int UserAdd(Users A)
{
Db.Userss.Add(A);
return Db.SaveChanges();
}
/// <summary>
/// 刪除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public int Del(int id)
{
var item = Db.Userss.Find(id);
Db.Userss.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.Userss.Remove(Db.Userss.Find(Convert.ToInt32(item)));
}
return Db.SaveChanges();
}
/// <summary>
/// 反填
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public Users FindById(int id)
{
return Db.Userss.Find(id);
}
/// <summary>
/// 修改
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public int Edit(Users user)
{
Db.Entry(user).State = System.Data.Entity.EntityState.Modified;
return Db.SaveChanges();
}
}

注意:再進行批量刪除的時候,要清晰邏輯:是將你選擇複選框設為陣列,然後對陣列進行迴圈遍歷,在迴圈遍歷的時候將陣列找到並轉化為int型別,然後在進行刪除

控制器

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

程式碼如下:

 UsersDal dal = new UsersDal();
// GET: Users
public ActionResult Index(int? TID, int? BID, int pageindex = 1, int pagesize = 3)
{
TypeXia();
BuMenXia();
int totalcount;
int totalpage;
var list = dal.ShowList(out totalcount, out totalpage, TID, BID, pageindex, pagesize);
var lilist = new StaticPagedList<Users>(list, pageindex, pagesize, totalcount);
ViewBag.totalcount = totalcount;
ViewBag.totalpage = totalpage;
ViewBag.pageindex = pageindex;
return View(lilist);
}
public void TypeXia()
{
ViewBag.TID = new SelectList(dal.LoadType(), "TID", "TName");
}
public void BuMenXia()
{
ViewBag.BID = new SelectList(dal.LoadBuMen(), "BID", "BName");
}
public void ChenXia()
{
ViewBag.CID = new SelectList(dal.LoadChen(), "CID", "CName");
}
/// <summary>
/// 新增檢視
/// </summary>
/// <returns></returns>
public ActionResult Add()
{
TypeXia();
BuMenXia();
ChenXia();
return View();
}
public ActionResult AddList(Users A)
{
if (dal.UserAdd(A) > 0)
{
return Content("<script>alert('新增成功');location.href='/Users/Index'</script>");
}
else
{
return Content("<script>alert('新增失敗');location.href='/Users/Add'</script>");
}
}
public ActionResult Del(int id)
{
if (dal.Del(id) > 0)
{
return Content("<script>alert('刪除成功');location.href='/Users/Index'</script>");
}
else
{
return Content("<script>alert('刪除失敗');location.href='/Users/Index'</script>");
}
}
public ActionResult dels(string ids)
{
if (dal.AllDel(ids) > 0)
{
return Content("<script>alert('刪除成功');location.href='/Users/Index'</script>");
}
else
{
return Content("<script>alert('刪除失敗');location.href='/Users/Index'</script>");
}
}
public ActionResult FindById(int id)
{
TypeXia();
BuMenXia();
ChenXia();
return View(dal.FindById(id));
}
public ActionResult Edit(Users users)
{
if (dal.Edit(users) > 0)
{
return Content("<script>alert('修改成功');location.href='/Users/Index'</script>");
}
else
{
return Content("<script>alert('修改失敗');location.href='/Users/Index'</script>");
}
}

}

檢視

在檢視中便是進行一個簡單的排版

新增:

@model MoNiYueKao.Models.Users

@{
ViewBag.Title = "Add";
}

<h2>Add</h2>
<form action="AddList" method="post">
<table class="table table-condensed">
<tr>
<td>招聘型別</td>
<td>
@Html.TextBoxFor(a => a.Zhao)
</td>
</tr>
<tr>
<td>類目</td>
<td>
@Html.DropDownListFor(a => a.TID, (SelectList)ViewBag.TID)
</td>
</tr>
<tr>
<td>用人部門</td>
<td>
@Html.DropDownListFor(a => a.BID, (SelectList)ViewBag.BID)
</td>
</tr>
<tr>
<td>職位名稱</td>
<td>
@Html.TextBoxFor(a => a.Name)
</td>
</tr>
<tr>
<td>工作城市</td>
<td>
@Html.DropDownListFor(a => a.CID, (SelectList)ViewBag.CID)
</td>
</tr>
<tr>
<td>是否急聘</td>
<td>
@Html.RadioButtonFor(a => a.JIzhao, true, new { @checked = "checked" })是
@Html.RadioButtonFor(a => a.JIzhao, false)否
</td>
</tr>
<tr>
<td>薪資範圍</td>
<td>
@Html.TextBoxFor(a => a.MinMoney, "", new { @placeholder = "最小值" })[email protected](a => a.MaxMoney, "", new { @placeholder = "最大值" })
</td>
</tr>
<tr>
<td>建立時間</td>
<td>
@Html.TextBoxFor(a=>a.CTime)
</td>
</tr>
<tr>
<td>描述該崗位的基礎資訊</td>
<td>
@Html.TextBoxFor(a => a.Xinxi)

</td>
</tr>
<tr>
<td>
<input type="submit" value="新增" />
</td>
</tr>
</table>
</form>

顯示:

@using PagedList;
@using PagedList.Mvc;
@model StaticPagedList<MoNiYueKao.Models.Users>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<form>
@Html.DropDownList("TID", (SelectList)ViewBag.TID, "類目")
@Html.DropDownList("BID", (SelectList)ViewBag.BID, "所屬部門")
<input type="submit" value="查詢" class="btn btn-default" />
<input type="button" value="批量刪除" class="btn btn-danger" onclick="Delete()" />
<input id="Button1" type="button" value="新增" onclick="location.href='/Users/Add'" class="btn btn-group" />
</form>
<table class="table table-condensed">
<thead>
<tr>
<td>
<input id="all" name="all" type="checkbox" />
</td>
<td>序號</td>
<td>招牌型別</td>
<td>類目</td>
<td>所屬部門</td>
<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.UID" />
</td>
<td>@item.UID</td>
<td>@item.Zhao</td>
<td>@item.UserType.TName</td>
<td>@item.UserBu.BName</td>
<td>@item.Name</td>
<td>@item.UserChen.CName</td>
<td>
@if (item.JIzhao == true)
{
<font color="green">是</font>
}
else
{
<font color="red">否</font>
}
</td>
<td>@[email protected]</td>
<td>@item.CTime</td>
<td>
<input id="Button1" type="button" value="編輯" class="btn btn-default" onclick="location.href = '[email protected]'" />
<input id="Button1" type="button" value="刪除" class="btn btn-danger" onclick="return confirm('確定刪除嗎?'); location.href = '[email protected]' " />
</td>
</tr>
}
</tbody>
</table>
@Html.PagedListPager(Model, pageindex => Url.Action("Index", new
{
TID = Request["TID"],
BID = Request["BID"],
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>
$("#all").click(function () {
$("[name=cbk]").prop("checked", this.checked);
})
function Delete() {
var arr = [];
$("[name=cbk]:checked").each(function () {
arr.push(this.value);
})
if (arr.length === 0) {
alert("請選擇要刪除的行");
return;
}
if (confirm("確定要刪除嗎?")) {
location.href = "dels?ids=" + arr.toString();
}
}
function Tiao() {
location.href = "/Users/Index?TID=@Request["TID"]&BID=@Request["TID"]&pageindex=" + $("#txt").val() + "&pagesize=3"
}
</script>
}

注意:在顯示的時候,要將分頁的頁數和條數,以及當前是多少頁進行顯示,在顯示第幾頁的時候,要拉一個文字框,然後在設立一個按鈕,點選按鈕,獲取文字框的值,並將文字框的值賦給第幾頁,然後進行跳轉,在跳轉的時候,我們使用的“鍵值對”的概念,就是直接將頁數跳轉到所對應的頁數:

反填及修改:

@model MoNiYueKao.Models.Users

@{
ViewBag.Title = "FindById";
}

<h2>FindById</h2>
<form action="Edit" method="post">
@Html.HiddenFor(a=>a.UID)
<table class="table table-condensed">
<tr>
<td>招聘型別</td>
<td>
@Html.TextBoxFor(a => a.Zhao)
</td>
</tr>
<tr>
<td>類目</td>
<td>
@Html.DropDownListFor(a => a.TID, (SelectList)ViewBag.TID)
</td>
</tr>
<tr>
<td>用人部門</td>
<td>
@Html.DropDownListFor(a => a.BID, (SelectList)ViewBag.BID)
</td>
</tr>
<tr>
<td>職位名稱</td>
<td>
@Html.TextBoxFor(a => a.Name)
</td>
</tr>
<tr>
<td>工作城市</td>
<td>
@Html.DropDownListFor(a => a.CID, (SelectList)ViewBag.CID)
</td>
</tr>
<tr>
<td>是否急聘</td>
<td>
@Html.RadioButtonFor(a => a.JIzhao, true, new { @checked = "checked" })是
@Html.RadioButtonFor(a => a.JIzhao, false)否
</td>
</tr>
<tr>
<td>薪資範圍</td>
<td>
@Html.TextBoxFor(a => a.MinMoney, "", new { @placeholder = "最小值" })[email protected](a => a.MaxMoney, "", new { @placeholder = "最大值" })
</td>
</tr>
<tr>
<td>建立時間</td>
<td>
@Html.TextBoxFor(a => a.CTime)
</td>
</tr>
<tr>
<td>描述該崗位的基礎資訊</td>
<td>
@Html.TextBoxFor(a => a.Xinxi)

</td>
</tr>
<tr>
<td>
<input type="submit" value="修改" />
</td>
</tr>
</table>

</form>

這樣之後,我們便完成一個簡單的EF的增刪改查頁面,以及所需要的一些小的功能