After using MVC for team development, I realized the convenience of object-oriented software development. When using MVC, the low coupling between layers makes the relationship between them very much, which reduces the degree of dependency between modules.
First, we will introduce the significance of MVC and the usage and functions between different layers.
1) entity layer. It is mainly used to declare the carrier for transferring data between the view layer and the business logic layer. It usually represents a meaningful record composed of one or more tables in the source and project database.
2) business logic layer. Provides data to the view layer according to the business logic. The class in this project has the right to decide whether to call the database access layer method based on the business logic.
3) database access layer. The business logic layer provides methods to access data.
4) view layer. This article mainly uses website development as an example. Displays, adds, edits, and deletes data.
The structure of the project I created in:
NetMVC is the so-called view layer. Entity is an Entity layer used to declare all variables to be used during development. DAL is the database access layer, mainly used to access the database through all operations. BLL is the business logic layer. It processes the business logic sent from the view layer and then passes it to the database access layer for processing.
This example mainly demonstrates the implementation of the login page. The Entity Layer Code is as follows:
Using System; using System. collections. generic; using System. text; namespace Entity {public class UserInfo {private int UserId; /// <summary> /// user ID // </summary> public int UserId1 {get {return UserId;} set {UserId = value ;}} private string username; // <summary> // Logon account name // </summary> public string Username {get {return username ;} set {username = value ;}} private string password; // <summary> // logon Password /// </summary> public string password {get {return password ;} set {password = value ;}} private int loginCount; // <summary> // Number of logins /// </summary> public int LoginCount {get {return loginCount ;} set {loginCount = value ;}} private DateTime regDate; // <summary> // registration time /// </summary> public DateTime RegDate {get {return regDate ;} set {regDate = value ;}} private DateTime lastLoginDate; /// <summary> /// last logon time /// </summary> public DateTime LastLoginDate {get {return lastLoginDate;} set {lastLoginDate = value ;}} private bool isForbidden; private string passwordQuestion; // <summary> // a password retrieval error is prompted. /// </summary> public string PasswordQuestion {get {return passwordQuestion ;} set {passwordQuestion = value ;}} private string passwordAnswer; /// <summary >/// retrieve the password /// </summary> public string PasswordAnswer {get {return passwordAnswer ;}set {passwordAnswer = value ;}}}}
To complete the creation of the object class, then we need to complete the creation of the database access layer (which needs to use the SqlHelper database access general class http://www.cnblogs.com/qq731109249/archive/2012/09/20/2694952.html written in the previous chapter), the Code is as follows,
Using System; using System. collections. generic; using System. text; using System. data; using System. data. sqlClient; using System. configuration; using Entity; namespace DAL {public class UserDal {private string connectionString = ConfigurationManager. connectionStrings ["connectionString"]. connectionString; /// <summary> /// Add User /// </summary> /// <param name = "info"> user entity class </param> /// <returns> </returns> public bool AddUser (UserInfo info) {string SQL = "insert into Users (Username, password) values ('@ username',' @ password')"; SqlParameter [] parameters = new SqlParameter [4]; parameters [0] = new SqlParameter ("@ Username", SqlDbType. NVarChar, 30); parameters [0]. value = info. username; parameters [1] = new SqlParameter ("password", SqlDbType. varChar, 50); parameters [1]. value = info. password; return new SqlDbHelper (connectionString ). executeNonQuery (SQL)> 0 ;} /// <summary> /// delete a user /// </summary> /// <param name = "UserId"> User ID </param> /// <returns> </returns> public bool DeleteUser (int UserId) {string SQL = "delete from users where UserId =" + UserId; return new SqlDbHelper (connectionString ). executeNonQuery (SQL)> 0 ;} /// <summary> /// update user /// </summary> /// <param name = "info"> user entity class </param> /// <returns> </returns> public bool UpDateUser (UserInfo info) {string SQL = "update users set password = @ password, loginCount = @ loginCount where userid = @ userid"; SqlParameter [] parameters = new SqlParameter [7]; parameters [0] = new SqlParameter ("@ password", SqlDbType. varChar, 30); parameters [0]. value = info. password; parameters [1] = new SqlParameter ("@ loginCount", SqlDbType. int, 4); parameters [1]. value = info. loginCount; return new SqlDbHelper (connectionString ). executeNonQuery (SQL)> 0 ;} /// <summary> /// query the user by user name or user number /// </summary> /// <param name = "userId"> User ID </param> /// <returns> </returns> public DataTable GetUser (int userId) {string SQL = "select * from users where userId = @ UserId"; SqlParameter [] parameters = new SqlParameter [1]; parameters [0] = new SqlParameter ("@ UserId ", sqlDbType. int, 4); parameters [0]. value = userId; return new SqlDbHelper (connectionString ). executeDataTable (SQL, CommandType. text, parameters );} /// <summary> /// query user information by user name /// </summary> /// <param name = "Username"> User name </param> /// <returns> </returns> public DataTable GetUser (string Username) {string SQL = "select * from users where username = @ username"; SqlParameter [] parameters = new SqlParameter [1]; parameters [1] = new SqlParameter ("@ username ", sqlDbType. NVarChar, 30); parameters [1]. value = Username; return new SqlDbHelper (connectionString ). executeDataTable (SQL, CommandType. text, parameters );} /// <summary> /// query the specified number of records starting from the specified position in ascending order of user numbers /// </summary> /// <param name = "startIndex"> Start position of the query </param> /// <param name = "size"> maximum number of returned records </param> /// <returns> </returns> public DataTable getUserList (int startIndex, int size) {string SQL = "select top" + size + "* from users where UserId not in (select top" + startIndex + "UserId from Users order by UserId asc) order by UserId asc "; return new SqlDbHelper (connectionString ). executeDataTable (SQL);} // <summary> // query the total number of users /// </summary> /// <returns> </returns> public int GetUserCount () {string SQL = "select count (1) from Users"; return int. parse (new SqlDbHelper (connectionString ). executeScalar (SQL ). toString ());}}}
Then, create the business logic layer. The Code is as follows:
Using System; using System. collections. generic; using System. text; using DAL; using Entity; using System. data; using System. data. sqlClient; using System. security. cryptography; using System. security; namespace BLL {public class UserBLL {private static string MD5Hash (string password) {MD5 md5 = MD5.Create (); // create an Md5 Algorithm instance // convert the original string to a byte array byte encoded by the UTF-8 [] sourceBytes = System. text. encoding. UTF8.GetBytes (password); // Calculate the hash value of the byte array byte [] resultBytes = md5.ComputeHash (sourceBytes); StringBuilder buffer = new StringBuilder (resultBytes. length); // convert each byte in the byte array of the calculated hash value to the hexadecimal format foreach (byte B in resultBytes) {buffer. append (B. toString ("X");} return buffer. toString ();} /// <summary> /// Add User /// </summary> /// <param name = "info"> user entity class </param> /// <returns> </returns> public static bool AddUser (UserInfo info) {UserDal dal = new UserDal (); DataTable data = dal. getUser (info. username); if (data. rows. count> 0) {return false;} else {info. password = MD5Hash (info. password); return new UserDal (). addUser (info );}} /// <summary> /// delete a user /// </summary> /// <param name = "userId"> User ID </param> /// <returns> </returns> public static bool DeleteUser (int userId) {return new UserDal (). deleteUser (userId);} // <sum Mary> /// update user /// </summary> /// <param name = "info"> user entity class </param> /// <param name = "changePassword"> whether to encrypt the User Password </param> // <returns> </returns> public static bool UpdateUser (UserInfo info, bool changePassword) {// if you change the password, you need to encrypt the new password. // if you do not change the password, you cannot re-encrypt the password. Otherwise, the user cannot log on to if (changePassword) {info. password = MD5Hash (info. password);} return new UserDal (). upDateUser (info);} // <summary> // query by user ID User /// </summary> /// <param name = "UserId"> User ID </param> /// <returns> </returns> public static DataTable GetUser (int UserId) {return new UserDal (). getUser (UserId );} /// <summary> /// query user information by user name /// </summary> /// <param name = "userName"> User name </param> /// <returns> </returns> public static DataTable GetUser (string userName) {return new UserDal (). getUser (userName) ;}/// <summary> /// locate by user ID in ascending order Set the specified number of records to start /// </summary> /// <param name = "startIndex"> Start position of the query </param> /// <param name = "size"> maximum number of returned records </param> // <returns> </returns> public static DataTable GetUserList (int startIndex, int size) {return new UserDal (). getUserList (startIndex, size );} /// <summary> /// query the total number of users /// </summary> /// <returns> </returns> public static int GetUserCount () {return new UserDal (). getUserCount ();} // <su Mmary> // query the object of the corresponding record from the database based on the user name or user number, if not, null // </summary> /// <param name = "userId"> User ID </param> /// <returns> </returns> public static UserInfo GetUserEntity (int userId) {return ChangeToEntity (new UserDal (). getUser (userId) ;}/// <summary> /// query the object of the corresponding record from the database based on the user name or user number, if not, null // </summary> /// <param name = "userName"> userName </param> /// <returns> </returns> public static userInfo GetUserEnt Ity (string userName) {return ChangeToEntity (new UserDal (). getUser (userName ));} /// <summary> /// convert the first record in the Ables that contains the Users table record to the Userinfo entity /// </summary> /// <param name = "data"> </param> // <returns> </returns> private static UserInfo ChangeToEntity (DataTable data) {UserInfo info = null; // if data is not empty and the number of records contained exceeds 0, if (data! = Null & data. rows. count> 0) {DataRow row = data. rows [0]; info = new UserInfo ();} return info;} public static bool Login (string userName, string password) {bool exits = false; userInfo info = GetUserEntity (userName); if (info! = Null & MD5Hash (password) = info. password) {exits = true; info. loginCount = info. loginCount + 1; // Add 1 info to the number of user logins. lastLoginDate = DateTime. now; // set the user's last logon time to the current UpdateUser (info, false); // update the user's logon times and last logon time} return exits ;}}}
This completes the creation of the database access layer, entity layer, and business logic layer. Because there are a lot of repetitive work during the creation process, I omitted some code to speed up the process.
When using the logon page, you only need to introduce the business logic layer method, and then input the corresponding parameters according to the method to complete all the operations.