MVC5 網站開發實踐 概述html
從這一部分開始作後臺管理,首先是基本框架的app
在Data項目的引用上右鍵-> 管理NuGet程序包。框架
在彈出的窗口中選擇 EntityFramework 安裝ide
在Data項目上點右鍵新建文件夾Type。在文件夾內添加類【OrderType】,代碼以下函數
//建立2014.12.8 namespace Data.Types { /// <summary> /// 排序類型 /// </summary> public enum OrderType { /// <summary> /// 不排序 /// </summary> No, /// <summary> /// 正序 /// </summary> Asc, /// <summary> /// 倒序 /// </summary> Desc } }
在Data項目上點右鍵新建類輸入類名【BaseRepository】,這個類主要負責數數據的存取。佈局
類內添加私有成員DbContext _baseDbContext用來在數據庫進行增、刪、改和查詢。網站
BaseRepository的構造函數public BaseRepository(DbContext dbContext)中dbContext爲數據上下文。在該類中寫了一些數據的增刪改和查詢方法。整個代碼以下。ui
using Ninesky.Data.Types; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; namespace Ninesky.Data { /// <summary> /// 數據倉儲基類 /// <remarks> /// 建立:2014.12.13 /// </remarks> /// </summary> /// <typeparam name="T"></typeparam> public class BaseRepository<T> where T : class { private DbContext _baseDbContext; /// <summary> /// 構造函數 /// </summary> /// <param name="dbContext">數據上下文</param> public BaseRepository(DbContext dbContext) { _baseDbContext = dbContext; } /// <summary> /// 添加 /// </summary> /// <param name="entity">數據實體</param> /// <param name="isSave">是否當即保存</param> /// <returns></returns> public T Add(T entity, bool isSave = true) { _baseDbContext.Set<T>().Add(entity); if (isSave) _baseDbContext.SaveChanges(); return entity; } /// <summary> /// 批量添加【當即執行】 /// </summary> /// <param name="entities">數據列表</param> /// <returns>添加的記錄數</returns> public int AddRange(IEnumerable<T> entities, bool isSave = true) { _baseDbContext.Set<T>().AddRange(entities); return isSave ? _baseDbContext.SaveChanges() : 0; } /// <summary> /// 修改 /// </summary> /// <param name="entity">數據實體</param> /// <param name="isSave">是否當即保存</param> /// <returns></returns> public bool Update(T entity, bool isSave = true) { _baseDbContext.Set<T>().Attach(entity); _baseDbContext.Entry<T>(entity).State = EntityState.Modified; return isSave ? _baseDbContext.SaveChanges() > 0 : true; } /// <summary> /// 刪除 /// </summary> /// <param name="entity">數據實體</param> /// <param name="isSave">是否當即保存</param> /// <returns></returns> public bool Delete(T entity, bool isSave = true) { _baseDbContext.Set<T>().Attach(entity); _baseDbContext.Entry<T>(entity).State = EntityState.Deleted; return isSave ? _baseDbContext.SaveChanges() > 0 : true; } /// <summary> /// 批量刪除 /// </summary> /// <param name="entities">數據列表</param> /// <param name="isSave">是否當即保存</param> /// <returns>刪除的記錄數</returns> public int DeleteRange(IEnumerable<T> entities, bool isSave = true) { _baseDbContext.Set<T>().RemoveRange(entities); return isSave ? _baseDbContext.SaveChanges() : 0; } /// <summary> /// 保存 /// </summary> /// <returns>受影響的記錄數</returns> public int Save() { return _baseDbContext.SaveChanges(); } /// <summary> /// 是否有知足條件的記錄 /// </summary> /// <param name="anyLamdba">條件表達式</param> /// <returns></returns> public bool Any(Expression<Func<T, bool>> anyLamdba) { return _baseDbContext.Set<T>().Any(anyLamdba); } /// <summary> /// 查詢記錄數 /// </summary> /// <param name="countLamdba">查詢表達式</param> /// <returns>記錄數</returns> public int Count(Expression<Func<T, bool>> countLamdba) { return _baseDbContext.Set<T>().Count(countLamdba); } /// <summary> /// 查找實體 /// </summary> /// <param name="ID">實體ID</param> /// <returns></returns> public T Find(int ID) { return _baseDbContext.Set<T>().Find(ID); } /// <summary> /// 查找實體 /// </summary> /// <param name="findLambda">Lambda表達式</param> /// <returns></returns> public T Find(Expression<Func<T, bool>> findLambda) { return _baseDbContext.Set<T>().SingleOrDefault(findLambda); } /// <summary> /// 查找全部列表 /// </summary> /// <returns></returns> public IQueryable<T> FindAll() { return FindList<int>(0, T => true, OrderType.No, null); } /// <summary> /// 查找數據列表 /// </summary> /// <param name="number">返回的記錄數【0-返回全部】</param> /// <param name="whereLandba">查詢條件</param> /// <param name="orderType">排序方式</param> /// <param name="orderLandba">排序條件</param> /// <returns></returns> public IQueryable<T> FindList<TKey>(int number, Expression<Func<T, bool>> whereLandba, OrderType orderType, Expression<Func<T, TKey>> orderLandba) { IQueryable<T> _tIQueryable = _baseDbContext.Set<T>().Where(whereLandba); switch (orderType) { case OrderType.Asc: _tIQueryable = _tIQueryable.OrderBy(orderLandba); break; case OrderType.Desc: _tIQueryable = _tIQueryable.OrderByDescending(whereLandba); break; } if (number > 0) _tIQueryable = _tIQueryable.Take(number); return _tIQueryable; } /// <summary> /// /// </summary> /// <typeparam name="TKey">排序字段類型</typeparam> /// <param name="pageIndex">頁碼【從1開始】</param> /// <param name="pageNumber">每頁記錄數</param> /// <param name="totalNumber">總記錄數</param> /// <param name="whereLandba">查詢表達式</param> /// <param name="orderType">排序類型</param> /// <param name="orderLandba">排序表達式</param> /// <returns></returns> public IQueryable<T> FindPageList<TKey>(int pageIndex, int pageNumber, out int totalNumber, Expression<Func<T, bool>> whereLandba, OrderType orderType, Expression<Func<T, TKey>> orderLandba) { IQueryable<T> _tIQueryable = _baseDbContext.Set<T>().Where(whereLandba); totalNumber = _tIQueryable.Count(); switch (orderType) { case OrderType.Asc: _tIQueryable = _tIQueryable.OrderBy(orderLandba); break; case OrderType.Desc: _tIQueryable = _tIQueryable.OrderByDescending(whereLandba); break; } _tIQueryable = _tIQueryable.Skip((pageIndex - 1) * pageNumber).Take(pageNumber); return _tIQueryable; } } }
在data項目右鍵添加【BaseService】,此類經過調用BaseRepository進行數據處理,做爲業務邏輯的基類,其餘業務類繼承自此類。這個類的方法與BaseRepository比較類似,創建此類的主要體現分層的思路,一些數據訪問的異常處理應該放在此類中。代碼以下:spa
using Ninesky.Data.Types; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; namespace Ninesky.Data { /// <summary> /// 業務邏輯基類 /// <remarks> /// 建立:2014.12.13 /// </remarks> /// </summary> public class BaseService<T> where T : class { private BaseRepository<T> _baseRepository; /// <summary> /// 建立業務邏輯類 /// </summary> /// <param name="dbContext">數據上下文</param> public BaseService(DbContext dbContext) { _baseRepository = new BaseRepository<T>(dbContext); } /// <summary> /// 添加 /// </summary> /// <param name="entity">數據實體</param> /// <returns>添加後的數據實體</returns> public T Add(T entity, bool isSave = true) { return _baseRepository.Add(entity, isSave); } ///// <summary> ///// 添加【必須先實例化才能使用】 ///// </summary> ///// <param name="entity">數據實體</param> ///// <returns>添加後的記錄ID</returns> //public virtual int Add(T entity) { return 0; } /// <summary> /// 批量添加 /// </summary> /// <param name="entities">數據列表</param> /// <param name="isSave">是否當即保存</param> /// <returns></returns> public int AddRange(IEnumerable<T> entities, bool isSave = true) { return _baseRepository.AddRange(entities, isSave); } /// <summary> /// 修改 /// </summary> /// <param name="entity">數據實體</param> /// <param name="isSave">是否當即保存</param> /// <returns></returns> public bool Update(T entity, bool isSave = true) { return _baseRepository.Update(entity, isSave); } /// <summary> /// 刪除 /// </summary> /// <param name="entity">數據實體</param> /// <param name="isSave">是否當即保存</param> /// <returns></returns> public bool Delete(T entity, bool isSave = true) { return _baseRepository.Delete(entity, isSave); } /// <summary> /// 批量刪除 /// </summary> /// <param name="entities">數據列表</param> /// <param name="isSave">是否當即保存</param> /// <returns>刪除的記錄數</returns> public int DeleteRange(IEnumerable<T> entities, bool isSave = true) { return _baseRepository.DeleteRange(entities, isSave); } /// <summary> /// 保存 /// </summary> /// <returns>受影響的記錄數</returns> public int Save() { return _baseRepository.Save(); } /// <summary> /// 查詢記錄數 /// </summary> /// <param name="countLamdba">查詢表達式</param> /// <returns>記錄數</returns> public int Count(Expression<Func<T, bool>> countLamdba) { return _baseRepository.Count(countLamdba); } /// <summary> /// 查找實體 /// </summary> /// <param name="ID">實體ID</param> /// <returns></returns> public T Find(int ID) { return _baseRepository.Find(ID); } /// <summary> /// 查找實體 /// </summary> /// <param name="findLambda">Lambda表達式</param> /// <returns></returns> public T Find(Expression<Func<T, bool>> findLambda) { return _baseRepository.Find(findLambda); } /// <summary> /// 查找全部列表 /// </summary> /// <returns></returns> public IQueryable<T> FindAll() { return _baseRepository.FindAll(); } /// <summary> /// 查找數據列表 /// </summary> /// <param name="number">返回的記錄數【0-返回全部】</param> /// <param name="whereLandba">查詢條件</param> /// <param name="orderType">排序方式</param> /// <param name="orderLandba">排序條件</param> /// <returns></returns> public IQueryable<T> FindList<TKey>(int number, Expression<Func<T, bool>> whereLandba, OrderType orderType, Expression<Func<T, TKey>> orderLandba) { return _baseRepository.FindList<TKey>(number, whereLandba, orderType, orderLandba); } /// <summary> /// /// </summary> /// <typeparam name="TKey">排序字段類型</typeparam> /// <param name="pageIndex">頁碼【從1開始】</param> /// <param name="pageNumber">每頁記錄數</param> /// <param name="totalNumber">總記錄數</param> /// <param name="whereLandba">查詢表達式</param> /// <param name="orderType">排序類型</param> /// <param name="orderLandba">排序表達式</param> /// <returns></returns> public IQueryable<T> FindPageList<TKey>(int pageIndex, int pageNumber, out int totalNumber, Expression<Func<T, bool>> whereLandba, OrderType orderType, Expression<Func<T, TKey>> orderLandba) { return FindPageList<TKey>(pageIndex, pageNumber, out totalNumber, whereLandba, orderType, orderLandba); } } }
在User項目的引用上點右鍵添加System.ComponentModel.DataAnnotations的引用和Ninesky.Data項目、E的引用。
在User項目上點右鍵新建文件夾Models,在文件夾中添加類Administrator。代碼以下:
using System; using System.ComponentModel.DataAnnotations; namespace Ninesky.User.Models { /// <summary> /// 管理員模型 /// <remarks> /// 建立:2014.12.13 /// </remarks> /// </summary> public class Administrator { [Key] public int AdministratorID { get; set; } /// <summary> /// 管理員帳號 /// </summary> [Required(ErrorMessage = "必須輸入{0}")] [Display(Name = "管理員帳號")] public string Account { get; set; } /// <summary> /// 管理員名稱 /// </summary> [Required(ErrorMessage = "必須輸入{0}")] [Display(Name = "管理員名稱")] public string Name { get; set; } /// <summary> /// 密碼 /// </summary> [Required(ErrorMessage = "必須輸入{0}")] [Display(Name = "密碼")] [DataType(DataType.Password)] public string Password { get; set; } /// <summary> /// 建立時間 /// </summary> public DateTime CreateDate { get; set; } /// <summary> /// 上次登錄Ip /// </summary> public string LoginIp { get; set; } /// <summary> /// 上次登錄日期 /// </summary> public Nullable<DateTime> LoginTime { get; set; } } }
在User項目上點右鍵添加AdministratorService類,該類繼承自BaseService。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ninesky.Data; using Ninesky.User.Models; namespace Ninesky.User { /// <summary> /// 管理員業務邏輯類 /// <remarks> /// 建立:2014.12.13 /// </remarks> /// </summary> public class AdministratorService:BaseService<Administrator> { public AdministratorService(DbContext dbContext) : base(dbContext) { } } }
在Site項目上點右鍵添加類【NineskyDbContext】,繼承自DbContext
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using Ninesky.User.Models; namespace Ninesky.Website { /// <summary> /// 網站數據上下文 /// <remarks> /// 建立:2014.12.13 /// </remarks> /// </summary> public class NineskyDbContext : DbContext { public DbSet<Administrator> Administrators { get; set; } public NineskyDbContext() : base("name=NineskyConnection") { Database.SetInitializer<NineskyDbContext>(new CreateDatabaseIfNotExists<NineskyDbContext>()); } } }
打開Web.config文件,在</configSections><appSettings>之間添加數據庫的鏈接
<connectionStrings> <add name="NineskyConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Ninesky.mdf;Initial Catalog=Ninesky;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" /> </connectionStrings>
在Website項目上點右鍵添加類【ContextFactory】,代碼以下:
using System.Runtime.Remoting.Messaging; namespace Ninesky.Website { /// <summary> /// 上下文簡單工廠 /// <remarks> /// 建立:2014.12.13 /// </remarks> /// </summary> public class ContextFactory { /// <summary> /// 獲取當前數據上下文 /// </summary> /// <returns>數據上下文</returns> public static NineskyDbContext GetCurrentContext() { NineskyDbContext _nineskyDbContext = CallContext.GetData("NineskyDbContext") as NineskyDbContext; if (_nineskyDbContext == null) { _nineskyDbContext = new NineskyDbContext(); CallContext.SetData("NineskyDbContext", _nineskyDbContext); } return _nineskyDbContext; } } }
在Site項目的Config區域的Controller文件夾上點右鍵添加Home控制器,類型選擇【MVC5控制器-空】。在添加的控制器中添加【Index】 action
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Ninesky.Website.Areas.Config.Controllers { /// <summary> /// 主界面 /// <remarks> /// 建立:2014.12.13 /// </remarks> /// </summary> public class HomeController : Controller { // GET: Config/Home public ActionResult Index() { return View(); } } }
在Config區域Views/Share文件夾添加布局頁【_Layout.cshtml】
在Index action上右鍵添加一個空視圖
===========================