程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> MVC項目結構搭建及單個類的實現學習筆記1,mvc學習筆記

MVC項目結構搭建及單個類的實現學習筆記1,mvc學習筆記

編輯:關於.NET

MVC項目結構搭建及單個類的實現學習筆記1,mvc學習筆記


新人剛開始學習ASP.NET MVC,若有不足之處希望能得到您的指點,不勝感激!

先來一張項目的層級結構圖:

Model:模型層,主要是各種類型、枚舉以及ORM框架,框架完成數據庫和實體類的映射。項目中選用了微軟的開源ORM框架 EntityFramework 6.0 (以下簡稱EF),數據庫則選擇了微軟的輕量級數據庫SQL Server Compact 4.0本地數據庫(簡稱Compact),Compact對EF支持比較完美,又屬於文檔型數據庫,部署起來比較簡潔。

DAL:數據訪問層,主要是對數據庫的操作層,為業務邏輯層或表示層提供數據服務。

IDAL:數據訪問接口層,是數據訪問層的接口,降低耦合。

DALFactory:數據會話層,封裝了所有數據操作類實例的創建,將數據訪問層與業務邏輯層解耦。

BLL:業務邏輯層,主要負責對數據層的操作,把一些數據層的操作進行組合以完成業務的需要。

IBLL:業務邏輯接口層,業務邏輯層的接口,降低耦合。

WebApp:表現層,是一個ASP.NET MVC項目,完成具體網站的實現。

Common:通用層,用來存放一些工具類。

下面是各個層級之間具體的實現,首先創建以 項目名.層級名 命名的各個層次,除WebApp層為ASP.NET MVC項目外,其余均創建為類庫項目。

模型層的構建

先建立模型層,新建ASP.NET 實體數據模型,關聯到已經設計好的數據庫,EF自動完成模型類的創建。

數據訪問層的構建

      DAL層中,我們首先需要一個方法來獲取單例的EF數據操縱上下文對象,以保證每個用戶訪問時只有使用一個上下文對象對數據庫進行操作。

DbContextFactory.cs

using System.Data.Entity;
using System.Runtime.Remoting.Messaging;
using PMS.Model;

namespace PMS.DAL
{
  public class DbContextFactory
  {
    /// <summary>
    /// 負責創建EF數據操作上下文實例,必須保證線程內唯一
    /// </summary>
    public static DbContext CreateContext()
    {
      DbContext dbContext = (DbContext)CallContext.GetData("dbContext");
      if (dbContext != null) return dbContext;
      dbContext = new PMSEntities();
      CallContext.SetData("dbContext", dbContext);
      return dbContext;
    }
  }
}

 

為User類創建DAL層,實現查詢、分頁查詢、增加、刪除和修改這五個基本的方法:

UserDAL.cs

using System;
using System.Data.Entity;
using System.Linq;
using PMS.IDAL;

namespace PMS.DAL
{
  public partial class UserDal   {
    public DbContext DbEntities = DbContextFactory.CreateContext();

    /// <summary>
    /// 查詢過濾
    /// </summary>
    /// <param name="whereLamada">過濾條件Lambda表達式</param>
    /// <returns>實體集合</returns>
    public IQueryable<UserDal> LoadEntities(System.Linq.Expressions.Expression<Func<UserDal, bool>> whereLamada)
    {
      return DbEntities.Set<UserDal>().Where(whereLamada);
    }

    /// <summary>
    /// 分頁查詢
    /// </summary>
    /// <typeparam name="TS">排序類型</typeparam>
    /// <param name="pageIndex">查詢的頁碼</param>
    /// <param name="pageSize">每頁顯示的數目</param>
    /// <param name="totalCount">符合條件的總行數</param>
    /// <param name="whereLambda">過濾條件Lambda表達式</param>
    /// <param name="orderbyLambda">排序Lambda表達式</param>
    /// <param name="isAsc">排序方向</param>
    /// <returns>實體集合</returns>
    public IQueryable<UserDal> LoadPageEntities<TS>(int pageIndex, int pageSize, out int totalCount, System.Linq.Expressions.Expression<Func<UserDal, bool>> whereLambda, System.Linq.Expressions.Expression<Func<UserDal, TS>> orderbyLambda, bool isAsc)
    {
      var temp = DbEntities.Set<UserDal>().Where(whereLambda);
      totalCount = temp.Count();
      temp = isAsc ? temp.OrderBy(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize) : temp.OrderByDescending(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize);
      return temp;
    }

    /// <summary>
    /// 刪除數據
    /// </summary>
    /// <param name="entity">待刪數據</param>
    /// <returns>刪除結果</returns>
    public bool DeleteEntity(UserDal entity)
    {
      DbEntities.Entry(entity).State = EntityState.Deleted;
      return true;
    }

    /// <summary>
    /// 編輯數據
    /// </summary>
    /// <param name="entity">待編輯數據</param>
    /// <returns>編輯結果</returns>
    public bool EditEntity(UserDal entity)
    {
      DbEntities.Entry(entity).State = EntityState.Modified;
      return true;
    }

    /// <summary>
    /// 添加數據
    /// </summary>
    /// <param name="entity">待添加數據</param>
    /// <returns>已添加數據</returns>
    public UserDal AddEntity(UserDal entity)
    {
      entity = DbEntities.Set<UserDal>().Add(entity);
      return entity;
    }    
  }
}

注:這裡的增刪改操作並不即時進行,而是在封裝在數據會話層中,以實現工作單元模式,提高數據庫的操作效率。

考慮到每個類都需要實現相同的數據操作,我們可以將以上方法封裝到一個泛型基類中,各類型只需要繼承泛型基類就可以實現以上方法:

BaseDal.cs

using System;
using System.Data.Entity;
using System.Linq;

namespace PMS.DAL
{
  public class BaseDal<T> where T:class ,new()
  {
    public DbContext DbEntities = DbContextFactory.CreateContext();

    /// <summary>
    /// 查詢過濾
    /// </summary>
    /// <param name="whereLamada">過濾條件Lambda表達式</param>
    /// <returns>實體集合</returns>
    public IQueryable<T> LoadEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLamada)
    {
      return DbEntities.Set<T>().Where(whereLamada);
    }

    /// <summary>
    /// 分頁查詢
    /// </summary>
    /// <typeparam name="TS">排序類型</typeparam>
    /// <param name="pageIndex">查詢的頁碼</param>
    /// <param name="pageSize">每頁顯示的數目</param>
    /// <param name="totalCount">符合條件的總行數</param>
    /// <param name="whereLambda">過濾條件Lambda表達式</param>
    /// <param name="orderbyLambda">排序Lambda表達式</param>
    /// <param name="isAsc">排序方向</param>
    /// <returns>實體集合</returns>
    public IQueryable<T> LoadPageEntities<TS>(int pageIndex, int pageSize, out int totalCount, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, TS>> orderbyLambda, bool isAsc)
    {
      var temp = DbEntities.Set<T>().Where(whereLambda);
      totalCount = temp.Count();
      temp = isAsc ? temp.OrderBy(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize) : temp.OrderByDescending(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize);
      return temp;
    }

    /// <summary>
    /// 刪除數據
    /// </summary>
    /// <param name="entity">待刪數據</param>
    /// <returns>刪除結果</returns>
    public bool DeleteEntity(T entity)
    {
      DbEntities.Entry(entity).State = EntityState.Deleted;
      return true;
    }

    /// <summary>
    /// 編輯數據
    /// </summary>
    /// <param name="entity">待編輯數據</param>
    /// <returns>編輯結果</returns>
    public bool EditEntity(T entity)
    {
      DbEntities.Entry(entity).State = EntityState.Modified;
      return true;
    }

    /// <summary>
    /// 添加數據
    /// </summary>
    /// <param name="entity">待添加數據</param>
    /// <returns>已添加數據</returns>
    public T AddEntity(T entity)
    {
      entity = DbEntities.Set<T>().Add(entity);
      //DbEntities.SaveChanges();
      return entity;
    }
  }
}

UserDal繼承BaseDal

using PMS.IDAL;
using PMS.Model;

namespace PMS.DAL
{
  public partial class UserDal : BaseDal<User>
  {
    
  }
}

數據訪問接口層的構建

然後我們建立相應的IbaseDal接口和IUserDal接口,並且使UserDal類實現IUserDal接口

IBaseDal:

using System;
using System.Linq;

namespace PMS.IDAL
{
  public interface IBaseDal<T> where T:class,new()
  {
    IQueryable<T> LoadEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLamada);

    IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount,
      System.Linq.Expressions.Expression<Func<T, bool>> whereLambda,
      System.Linq.Expressions.Expression<Func<T, s>> orderbyLambda, bool isAsc);

    bool DeleteEntity(T entity);
    
    bool EditEntity(T entity);

    T AddEntity(T entity);
  }
}

IUserDal:

using PMS.Model;
namespace PMS.IDAL
{
  public partial interface IUserDal:IBaseDal<User>
  {

  }
}

UserDal實現IUserDal接口:

public partial class UserDal : BaseDal<User>,IUserDal

數據會話層的構建

抽象工廠類AbstractFactory:

using System.Configuration;
using System.Reflection;
using PMS.IDAL;

namespace PMS.DALFactory
{
  public partial class AbstractFactory
  {
    //讀取保存在配置文件中的程序集名稱與命名空間名
    private static readonly string AssemblyPath = ConfigurationManager.AppSettings["AssemblyPath"];
    private static readonly string NameSpace = ConfigurationManager.AppSettings["NameSpace"];
    /// <summary>
    /// 獲取UserDal的實例
    /// </summary>
    /// <returns></returns>
    public static IUserDal CreateUserInfoDal()
    {
      var fullClassName = NameSpace + ".UserInfoDal";
      return CreateInstance(fullClassName) as IUserDal;
    }
    /// <summary>
    /// 通過反射獲得程序集中某類型的實例
    /// </summary>
    /// <param name="className"></param>
    /// <returns></returns>
    private static object CreateInstance(string className)
    {
      var assembly = Assembly.Load(AssemblyPath);
      return assembly.CreateInstance(className);
    }
  }
}

數據會話類DbSession:

using System.Data.Entity;
using PMS.IDAL;
using PMS.DAL;

namespace PMS.DALFactory
{
  public partial class DbSession:IDbSession
  {
    public DbContext Db
    {
      get { return DbContextFactory.CreateContext(); }
    }

    private IUserDal _userDal;
    public IUserDal UserDal
    {
      get { return _userDal ?? (_userDal = AbstractFactory.CreateUserInfoDal()); }
      set { _userDal = value; }
    }

    /// <summary>
    /// 工作單元模式,統一保存數據
    /// </summary>
    /// <returns></returns>
    public bool SaveChanges()
    {
      return Db.SaveChanges() > 0;
    }
  }
}

業務邏輯層的構建

業務類基類BaseService

using System;
using System.Linq;
using System.Linq.Expressions;
using PMS.DALFactory;
using PMS.IDAL;

namespace PMS.BLL
{
  public abstract class BaseService<T> where T:class,new()
  {
    public IDbSession CurrentDbSession
    {
      get
      {
        return new DbSession();
      }
    }
    public IBaseDal<T> CurrentDal { get; set; }
    public abstract void SetCurrentDal();
    public BaseService()
    {
      SetCurrentDal();//子類一定要實現抽象方法,以指明當前類的子類類型。
    }

    /// <summary>
    /// 查詢過濾
    /// </summary>
    /// <param name="whereLambda"></param>
    /// <returns></returns>
    public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
    {
      return CurrentDal.LoadEntities(whereLambda);
    }

    /// <summary>
    /// 分頁
    /// </summary>
    /// <typeparam name="s"></typeparam>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="totalCount"></param>
    /// <param name="whereLambda"></param>
    /// <param name="orderbyLambda"></param>
    /// <param name="isAsc"></param>
    /// <returns></returns>
    public IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, Expression<Func<T, bool>> whereLambda,
      Expression<Func<T, s>> orderbyLambda, bool isAsc)
    {
      return CurrentDal.LoadPageEntities<s>(pageIndex, pageSize, out totalCount, whereLambda, orderbyLambda, isAsc);
    }

    /// <summary>
    /// 刪除
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public bool DeleteEntity(T entity)
    {
      CurrentDal.DeleteEntity(entity);
      return CurrentDbSession.SaveChanges();
    }

    /// <summary>
    /// 編輯
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public bool EditEntity(T entity)
    {
      CurrentDal.EditEntity(entity);
      return CurrentDbSession.SaveChanges();
    }

    /// <summary>
    /// 添加數據
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public T AddEntity(T entity)
    {
      CurrentDal.AddEntity(entity);
      CurrentDbSession.SaveChanges();
      return entity;
    }
  }
}

UserService類:

using PMS.IBLL;
using PMS.Model;

namespace PMS.BLL
{
  public partial class UserService : BaseService<User>
  {
    public override void SetCurrentDal()
    {
      CurrentDal = CurrentDbSession.UserDal;
    }
  }
}

 

業務邏輯接口層的構建

直接建立對應的接口並使用UserService類實現IUserService接口

IBaseService接口:

using System;
using System.Linq;
using System.Linq.Expressions;
using PMS.IDAL;

namespace PMS.IBLL
{
  public interface IBaseService<T> where T : class,new()
  {
    IDbSession CurrentDbSession { get; }
    IBaseDal<T> CurrentDal { get; set; }
    void SetCurrentDal();
    IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda);

    IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount,
      Expression<Func<T, bool>> whereLambda,
      Expression<Func<T, s>> orderbyLambda, bool isAsc);

    bool DeleteEntity(T entity);
    bool EditEntity(T entity);
    T AddEntity(T entity);
  }
}

IUserService接口:

using PMS.Model;

namespace PMS.IBLL
{
  public partial interface IUserService:IBaseService<User>
  {

  }
}

使用UserService類實現IUserService接口:

public partial class UserService : BaseService<User>, IUserService  

以上我們就完成了整個框架中關於User類的各層次的實現。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持幫客之家。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved