MVC project structure construction and implementation of a single class Study Notes 1. mvc Study Notes
Newcomers are just starting to learn ASP. net mvc. If you have any shortcomings, I hope you can give me some advice. Thank you very much!
Let's take a look at the hierarchical structure of a Project:
Model: Model layer, mainly for various types, enumeration and ORM frameworks. The framework maps databases and entity classes. The project selects Microsoft's open-source ORM framework EntityFramework 6.0 (hereinafter referred to as EF), and the database selects Microsoft's lightweight Database SQL Server Compact 4.0 local database (hereinafter referred to as Compact ), compact provides perfect support for EF and is also a document-type database, which is relatively simple to deploy.
DAL: the data access layer, mainly the database operation layer, provides data services for the business logic layer or presentation layer.
IDAL: the data access interface layer is the interface of the data access layer, reducing coupling.
DALFactory: a data Session Layer that encapsulates the creation of all data operation instances and decouples the data access layer from the business logic layer.
BLL: business logic layer. It is mainly responsible for operations on the data layer and combines operations on some data layers to meet business needs.
IBLL: interfaces at the business logic interface layer and business logic layer reduce coupling.
WebApp: The presentation layer. It is an ASP. net mvc project to implement a specific website.
Common: A Common layer used to store some tool classes.
The following describes the implementation of each level. First, create a layer named after the project name. Hierarchy name. Except that the WebApp layer is an ASP. net mvc project, all other layers are created as class library projects.
Model Layer Construction
First, create a model layer, create an ASP. NET Entity Data Model, and associate it with the designed database. EF automatically creates the model class.
Data access layer Construction
In the DAL layer, we first need a method to obtain the EF data of a single instance to manipulate the context object, so that each user can only use one context object to operate the database during access.
DbContextFactory. cs
Using System. data. entity; using System. runtime. remoting. messaging; using PMS. model; namespace PMS. DAL {public class DbContextFactory {// <summary> // creates an EF data operation context instance, it must be unique in the thread // </summary> public static DbContext CreateContext () {DbContext dbContext DbContext = (DbContext) CallContext. getData ("dbContext"); if (dbContext! = Null) return dbContext; dbContext = new PMSEntities (); CallContext. SetData ("dbContext", dbContext); return dbContext ;}}}
Create a DAL layer for the User class to implement the following basic methods: Query, paging query, add, delete, and modify:
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> /// query filtering /// </summary> /// <param name = "whereLamada"> filter condition Lambda expression </param> /// <returns> entity set </returns> public IQueryable <UserDal> LoadEntities (System. linq. expressions. expression <Func <UserDal, bool> wh EreLamada) {return DbEntities. set <UserDal> (). where (whereLamada );} /// <summary> /// query by PAGE /// </summary> /// <typeparam name = "TS"> sorting type </typeparam> /// <param name = "pageIndex"> page number </param> // <param name = "pageSize"> Number of entries displayed on each page </param> // <param name = "totalCount"> total number of qualified rows </param> // <param name = "whereLambda"> filter condition Lambda expression </param> // <param name =" orderbyLambda "> sort Lambda expressions </param> // <param name =" IsAsc "> sorting direction </param> // <returns> entity set </returns> public IQueryable <UserDal> LoadPageEntities <TS> (int pageIndex, int pageSize, out int totalCount, System. linq. expressions. expression <Func <UserDal, bool> wherelamdal, System. linq. expressions. expression <Func <UserDal, TS> orderbyLambda, bool isAsc) {var temp = DbEntities. set <UserDal> (). where (wherelamcount); 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> /// delete data /// </summary> /// <param name = "entity"> data to be deleted </param> // <returns> Delete result </returns> public bool DeleteEntity (UserDal entity) {DbEntities. entry (entity ). state = EntityState. deleted; return true ;} /// <summary> /// edit data /// </summary> /// <param name = "entity"> data to be edited </param> // <returns> edit result </returns> public bool EditEntity (UserDal entity) {DbEntities. entry (entity ). state = EntityState. modified; return true ;} /// <summary> /// add data /// </summary> /// <param name = "entity"> data to be added </param> // <returns> added data </returns> public UserDal AddEntity (UserDal entity) {entity = DbEntities. set <UserDal> (). add (entity); return entity ;}}}
Note:The addition, deletion, and modification operations are not performed in real time, but are encapsulated in the Data Session Layer to Implement the work unit mode and improve the database operation efficiency.
Considering that each class needs to implement the same data operation, we can encapsulate the above methods into a generic base class. Each type only needs to inherit the generic base class to implement the above methods:
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> /// query filtering /// </summary> /// <param name = "whereLamada"> filter condition Lambda expression </param> /// <returns> entity set </returns> public IQueryable <T> LoadEntities (System. linq. expressions. expression <Func <T, bool> whereLamada) {Return DbEntities. set <T> (). where (whereLamada );} /// <summary> /// query by PAGE /// </summary> /// <typeparam name = "TS"> sorting type </typeparam> /// <param name = "pageIndex"> page number </param> // <param name = "pageSize"> Number of entries displayed on each page </param> // <param name = "totalCount"> total number of qualified rows </param> // <param name = "whereLambda"> filter condition Lambda expression </param> // <param name =" orderbyLambda "> sort Lambda expression </param> // <param name =" isAsc "> sort direction </para M> // <returns> entity set </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 (wherelamcount); 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> /// delete data /// </summary> /// <param name = "entity"> data to be deleted </param> // <returns> Delete result </returns> public bool DeleteEntity (T entity) {DbEntities. entry (entity ). state = EntityState. deleted; return true ;} /// <summary> /// edit data /// </summary> /// <param name = "entity"> data to be edited </param> // <returns> edit result </returns> public bool EditEntity (T entity) {DbEntities. entry (entity ). state = EntityState. modified; return true ;} /// <summary> /// add data /// </summary> /// <param name = "entity"> data to be added </param> // <returns> added data </returns> public T AddEntity (T entity) {entity = DbEntities. set <T> (). add (entity); // DbEntities. saveChanges (); return entity ;}}}
UserDal inherits BaseDal
using PMS.IDAL;using PMS.Model;namespace PMS.DAL{ public partial class UserDal : BaseDal<User> { }}
Data access interface layer Construction
Then we establish the corresponding IbaseDal interface and IUserDal interface, and make the UserDal class implement the IUserDal interface.
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 implements the IUserDal interface:
Public partial class UserDal: BaseDal <User>, IUserDal
Build the data Session Layer
AbstractFactory:
Using System. configuration; using System. reflection; using PMS. IDAL; namespace PMS. DALFactory {public partial class AbstractFactory {// read the Assembly name and namespace name saved in the configuration file private static readonly string AssemblyPath = ConfigurationManager. appSettings ["AssemblyPath"]; private static readonly string NameSpace = ConfigurationManager. appSettings ["NameSpace"]; /// <summary> /// obtain the UserDal instance /// </summary> /// <returns> </returns> public static IUserDal CreateUserInfoDal () {var fullClassName = NameSpace + ". userInfoDal "; return CreateInstance (fullClassName) as IUserDal ;} /// <summary> /// obtain a certain type of instance in the Assembly through reflection // </summary> /// <param name = "className"> </param> /// <returns> </returns> private static object CreateInstance (string className) {var assembly = Assembly. load (AssemblyPath); return assembly. createInstance (className );}}}
Data session 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> // work unit mode, save data in a unified manner /// </summary> /// <returns> </returns> public bool SaveChanges () {return Db. saveChanges ()> 0 ;}}}
Construction of the business logic layer
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 (); // The subclass must implement the abstract method, to specify the subclass type of the current class.} /// <Summary> /// query filtering /// </summary> /// <param name = "whereLambda"> </param> /// <returns> </returns> public IQueryable <T> LoadEntities (Expression <Func <T, bool> wherelamloud) {return CurrentDal. loadEntities (wherelamties );} /// <summary> /// paging /// </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, wherelamties, orderbyLambda, isAsc );} /// <summary> /// Delete /// </summary> /// <param name = "entity"> </param> /// <returns> </ returns> public bool DeleteEntity (T entity) {CurrentDal. deleteEntity (entity); return CurrentDbSession. saveChanges ();} /// <summary> /// edit /// </summary> /// <param name = "entity"> </param> /// <returns> </ returns> public bool EditEntity (T entity) {CurrentDal. editEntity (entity); return CurrentDbSession. saveChanges ();} /// <summary> /// add data /// </summary> /// <param name = "entity"> </param> /// <returns> </returns> public T AddEntity (T entity) {CurrentDal. addEntity (entity); CurrentDbSession. saveChanges (); return entity ;}}}
UserService class:
using PMS.IBLL;using PMS.Model;namespace PMS.BLL{ public partial class UserService : BaseService<User> { public override void SetCurrentDal() { CurrentDal = CurrentDbSession.UserDal; } }}
Construction of business logic interface layer
Directly create the corresponding interface and use the UserService class to implement the IUserService Interface
IBaseService interface:
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 interface:
using PMS.Model;namespace PMS.IBLL{ public partial interface IUserService:IBaseService<User> { }}
Use the UserService class to implement the IUserService interface:
Public partial class UserService: BaseService <User>, IUserService
The above completes the implementation of the User class layers in the entire framework.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.