Construction of MVC project structure and realization of single class learning notes 1_ practical skills

Source: Internet
Author: User
Tags compact reflection

New people just began to learn asp.net MVC, if there is a shortage of hope to get your advice, appreciate!

Let's start with a hierarchical chart of the projects:

Model: Models layer, mainly various types, enumerations and ORM Framework, the framework completes the database and entity class mapping. Microsoft's Open source ORM Framework EntityFramework 6.0 (EF) is selected in the project, and the database selects Microsoft's lightweight database SQL Server Compact 4.0 local Database (compact). The Compact for EF support is perfect, but also belongs to the document database, the deployment is relatively concise.

DAL: A data access layer that provides data services to the business logic layer or presentation layer, primarily to the operational layer of the database.

Idal: Data access interface layer, is the interface of data access layer, reduce coupling.

Dalfactory: The data session layer encapsulates the creation of all data manipulation class instances, decoupling the data access layer from the business logic layer.

BLL: The business Logic layer, which is mainly responsible for the operation of the data layer, the operation of some data layers are combined to fulfill the business needs.

IBLL: Business logic interface layer, business logic layer interface, reduce coupling.

WEBAPP: Performance layer, is a asp.net MVC project, complete the implementation of specific Web sites.

Common: Common layer, used to store some tool classes.

The following is a concrete implementation between tiers, first creating each level named after the name of the project, except that the WebApp layer is the ASP.net MVC project, and the rest is created as a class library project.

Construction of Model layer

First build the model layer, create a new asp.net entity Data model, correlate to the already designed database, EF automates the creation of model classes.

The construction of data access layer

In the DAL layer, we first need a method to obtain a single example of the EF data manipulation context object to ensure that each user accesses the database using only one context object.

DbContextFactory.cs

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

Namespace PMS. DAL
{public
  class Dbcontextfactory
  {
    ///<summary>
    ///is responsible for creating an EF data operation context instance that must be guaranteed to be unique within the thread
    // /</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;
    }
  }


Create a DAL layer for the user class that implements the five basic methods of querying, paging queries, adding, deleting, and modifying:

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 Filter///</summary>///<param name= "Wherelamada" > Filter conditions lambda expression </param&
    Gt <returns> Entity Collection </returns> public iqueryable<userdal> loadentities ( System.linq.expressions.expression<func<userdal, bool>> Wherelamada) {return DbEntities.Set<User Dal> ().
    Where (Wherelamada); 
    ///<summary>///Paging query///</summary>///<typeparam name= "TS" > Sort type </typeparam>
    <param name= "PageIndex" > Query page Numbers </param>///<param name= "PageSize" > Number of per page </param> <param name= "TotalCount" > Eligible total rows </param>///<param name= "WHERELAMBDA" > Filter conditions lambda expression </ param>///<param name= "Orderbylambda" > Sort lambdA expression </param>///<param name= "ISASC" > Sort Direction </param>///<returns> entity collection </returns> PU Blic 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 = DbEnti Ties. Set<userdal> ().
      Where (WHERELAMBDA); TotalCount = temp.
      Count (); temp = ISASC? Temp. by (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" > Pending deletion of Data </param> <returns> Delete results </returns> public bool Deleteentity (Userdal entity) {Dbentities.entry (entity) .
      state = entitystate.deleted;return true;
    ///<summary>///Edit Data///</summary>///<param name= "entity" > Pending editing Data </param> <returns> Edit Results </returns> public bool Editentity (Userdal entity) {Dbentities.entry (entity).
      state = entitystate.modified;
    return true;
    ///<summary>///Add data///</summary>///<param name= "entity" > Add Data </param> <returns> added data </returns> public userdal addentity (Userdal entity) {entity = dbentities.se T<userdal> ().
      ADD (entity);
    return entity;

 }    
  }
}

Note: here the additions and deletions are not performed immediately, but are encapsulated in the data session layer to realize the Working Unit mode and improve the operation efficiency of the database.

Given that each class needs to implement the same data operations, we can encapsulate the above methods in a generic base class, which can be implemented only if the generic base class is inherited by a variety of types:

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.createco

    ntext (); <summary>///query Filter///</summary>///<param name= "Wherelamada" > Filter conditions lambda expression </param&
    Gt <returns> Entity Collection </returns> public iqueryable<t> loadentities (System.Linq.Expressions.Expression <func<t, bool>> Wherelamada) {return dbentities.set<t> ().
    Where (Wherelamada); 
    ///<summary>///Paging query///</summary>///<typeparam name= "TS" > Sort type </typeparam>
    <param name= "PageIndex" > Query page Numbers </param>///<param name= "PageSize" > Number of per page </param> <param name= "TotalCount" > Eligible total rows </param>///<param name= "WHERELAMBDA" > Filter conditions lambda expression </ param>///<param name= "Orderbylambda" > Sort lambda expression </param>///<param name= "ISASC" > Sort Direction </param>///<returns> entity collection </returns> public Iquerya ble<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. by (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" > Pending deletion of Data </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" > Pending edit Data </param>///<returns> Edit Results </r Eturns> public bool Editentity (T entity) {Dbentities.entry (entity).
      state = entitystate.modified;
    return true;
    ///<summary>///Add data///</summary>///<param name= "entity" > Add Data </param> <returns> added data </returns> public T addentity (t entity) {entity = dbentities.set<t> () .
      ADD (entity);
      Dbentities.savechanges ();
    return entity;

 }
  }
}

Userdal Inheritance Basedal

Using PMS. Idal;
Using PMS. Model;

Namespace PMS. DAL
{public
  partial class userdal:basedal<user>
  {
    
  }
}

Construction of data access interface layer

Then we establish the corresponding Ibasedal interface and Iuserdal interface, and make the Userdal class implement 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

Construction of data Session layer

Abstract Factory class Abstractfactory:

Using System.Configuration;
Using System.Reflection; Using PMS.

Idal; Namespace PMS. dalfactory {public partial class Abstractfactory {//Read the assembly name saved in the configuration file with the namespace name private static readonly string as
    Semblypath = configurationmanager.appsettings["AssemblyPath"];
    private static readonly string NameSpace = configurationmanager.appsettings["NameSpace"]; <summary>///Get Userdal instance///</summary>///<returns></returns> public Stati C Iuserdal Createuserinfodal () {var fullclassname = NameSpace + ".
      Userinfodal ";
    Return CreateInstance (FullClassName) as Iuserdal; ///<summary>///obtains an instance of a type in an assembly through reflection///</summary>///<param name= "ClassName" ></par am>///<returns></returns> private static Object CreateInstance (String className) {var
      Assembly = Assembly.Load (AssemblyPath); return assembly.
    CreateInstance (ClassName);

 }
  }
}

Data Session Class Dbsession:

Using System.Data.Entity;
Using PMS. Idal;
Using PMS. DAL;

Namespace PMS. Dalfactory
{public
  partial class dbsession:idbsession
  {public
    dbcontext Db
    {get
      } Dbcontextfactory.createcontext (); }

    private iuserdal _userdal;
    Public Iuserdal userdal
    {get
      {return _userdal?? (_userdal = Abstractfactory.createuserinfodal ());
      set {_userdal = value;}
    }

    <summary>
    ///Working unit mode, unified data
    ///</summary>
    ///<returns></returns> Public
    bool SaveChanges ()
    {return
      db.savechanges () > 0;
    }
  }
}

The construction of the business logic layer

Business class base class 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 an abstract method to indicate the subclass type of the current class.
    ///<summary>///query filter///</summary>///<param name= "Wherelambda" ></param> <returns></returns> public iqueryable<t> loadentities (expression<func<t, bool>> wh
    ERELAMBDA) {return currentdal.loadentities (WHERELAMBDA); ///<summary>///Paging///</summary>///<typeparam name= "s" ></typeparam>// /<param name= "PageIndex" ></param>///<param name= "PageSize"></param>///<param name= "TotalCount" ></param>///<param name= "Wherelambda" ></para m>///<param name= "Orderbylambda" ></param>///<param name= "ISASC" ></param>///&L T;returns></returns> public iqueryable<t> loadpageentities<s> (int pageIndex, int pageSize, out in T TotalCount, Expression<func<t, bool>> Wherelambda, expression<func<t, s>> OrderbyLambda, b Ool isasc) {return currentdal.loadpageentities<s> (PageIndex, pageSize, out TotalCount, WHERELAMBDA, order
    Bylambda, ISASC); }///<summary>///delete///</summary>///<param name= "entity" ></param>///&
      Lt;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) {Cu
      Rrentdal.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;
    }
}}

The construction of business logic interface layer

directly establish the corresponding interface and implement the Iuserservice interface using the UserService class

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>
  {

  }
}

Implement the Iuserservice interface using the UserService class:

public partial class Userservice:baseservice<user>, Iuserservice

We have completed the implementation of all levels of the user class in the entire framework.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.