EF增刪改查by糟糕的代碼
上一講我們創建了一系列的解決方案,我們通過一個例子來看看層與層之間的關系。
我們把Controllers分離出來了BLL層和DAL層
BLL專注於業務上的處理
DAL專注於數據訪問層的處理
而Controller跟清楚的與View交互
我們上一講已經在EF添加了一個實體SysSample
下面我們創建IDAL,DAL,IBLL,BLL的代碼吧
using App.Models; using System.Linq; namespace App.IDAL { public interface ISysSampleRepository { /// <summary> /// 獲取列表 /// </summary> /// <param name="db">數據庫上下文</param> /// <returns>數據列表</returns> IQueryable<SysSample> GetList(DBContainer db); /// <summary> /// 創建一個實體 /// </summary> /// <param name="entity">實體</param> int Create(SysSample entity); /// <summary> /// 刪除一個實體 /// </summary> /// <param name="entity">主鍵ID</param> int Delete(string id); /// <summary> /// 修改一個實體 /// </summary> /// <param name="entity">實體</param> int Edit(SysSample entity); /// <summary> /// 獲得一個實體 /// </summary> /// <param name="id">id</param> /// <returns>實體</returns> SysSample GetById(string id); /// <summary> /// 判斷一個實體是否存在 /// </summary> bool IsExist(string id); } } ISysSampleRepository.cs
using System; using System.Linq; using App.IDAL; using App.Models; using System.Data; namespace App.DAL { public class SysSampleRepository : ISysSampleRepository, IDisposable { /// <summary> /// 獲取列表 /// </summary> /// <param name="db">數據庫上下文</param> /// <returns>數據列表</returns> public IQueryable<SysSample> GetList(DBContainer db) { IQueryable<SysSample> list = db.SysSample.AsQueryable(); return list; } /// <summary> /// 創建一個實體 /// </summary> /// <param name="db">數據庫上下文</param> /// <param name="entity">實體</param> public int Create(SysSample entity) { using (DBContainer db = new DBContainer()) { db.SysSample.AddObject(entity); return db.SaveChanges(); } } /// <summary> /// 刪除一個實體 /// </summary> /// <param name="db">數據庫上下文</param> /// <param name="entity">主鍵ID</param> public int Delete(string id) { using (DBContainer db = new DBContainer()) { SysSample entity = db.SysSample.SingleOrDefault(a => a.Id == id); if (entity != null) { db.SysSample.DeleteObject(entity); } return db.SaveChanges(); } } /// <summary> /// 修改一個實體 /// </summary> /// <param name="db">數據庫上下文</param> /// <param name="entity">實體</param> public int Edit(SysSample entity) { using (DBContainer db = new DBContainer()) { db.SysSample.Attach(entity); db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); return db.SaveChanges(); } } /// <summary> /// 獲得一個實體 /// </summary> /// <param name="id">id</param> /// <returns>實體</returns> public SysSample GetById(string id) { using (DBContainer db = new DBContainer()) { return db.SysSample.SingleOrDefault(a => a.Id == id); } } /// <summary> /// 判斷一個實體是否存在 /// </summary> /// <param name="id">id</param> /// <returns>是否存在 true or false</returns> public bool IsExist(string id) { using (DBContainer db = new DBContainer()) { SysSample entity = GetById(id); if (entity != null) return true; return false; } } public void Dispose() { } } }