[ASP. NET development] Simple parsing of. NET three-layer architecture

Source: Internet
Author: User

For a three-tier architecture, classes are used to abstract some objects of the common nature in the project process. Of course, this is also part of object-oriented. The three layers refer to: ① entity layer ② database access layer ③ business logic layer. Of course, all these three layers are eventually serving a layer, that is, the so-called view layer, but why is it not called a layer-4 architecture... I don't know the reason. It may be that the view layer only completes some calls to the business logic layer, which is constantly changing and can be compiled as needed. The other three layers can be used as the framework after construction. 1) Let's first introduce the Entity layer. Entity entities are the objects we usually refer to in the development project process. Abstract The objects to be involved (such as news names, news upload times, contributors, and names of uploaded files) into a class. By using the encapsulated field method, we can assign values to the attributes of an object at the view layer (mainly the view layer) by instantiating the object. Simply look at a piece of code. It may be clearer to understand public class NewsModel {// news number private int nNewsId; public int NNewsId {get {return nNewsId ;} set {nNewsId = value ;}/// news name private string strNewsName; public string StrNewsName {get {return strNewsName ;}set {strNewsName = value ;}}} newsModel is an entity class about news. It declares two attribute fields of private (private must be used to prevent illegal assignment) and uses the public constructor, field values can be assigned externally. The following describes how to instantiate an object in the view layer and assign values to fields as needed. See the following code: NewsModel newModel = new NewsModel (); newModel. strNewsName = this. textBox1.Text; of course, this is just a piece of code, which does not assign a value to the field nNewsId, because I have set it as the id location of the database and it has been set to automatically grow. In this way, the view layer calls the Object layer. 2) database access layer the database access layer, as its name implies, is mainly used to access the database and perform database operations in a series. Why do we need to abstract database operations into a separate class separately? I personally understand that in the whole project development process, we need to access the database not only once, but also multiple times, if you write the database access code every time, it will increase the workload of the programmer, and it must be very bad for the ease of use and simplicity of the Code. Of course, there may be some other advantages that I have not found yet. Since it is a database operation class and database operations, there are only four types: add, delete, modify, and query. Therefore, a common class that provides addition, deletion, modification, and query is essential. This is what we often call the generic database helper class (many programmers like to name this class SqlHelper. Since it is a name, it can be freely started, as long as it does not violate the naming rules of C # syntax, it is also advantageous that other programmers can determine what the class is to do based on the class name ). Of course, when I was working on my own project this time, the database category class I wrote was not as complex as the database category class I copied when I read the book by Mr. Zhou Jinqiao. NET Development] ASP.. NET for the general database category of SQLServer). Of course, my database category here is mainly for the sake of introduction and ease of use, as long as it meets the needs of my current project, not every project, write a fully functional database category. The Code is as follows. For more information, see which category class you prefer. You can use it directly based on your own taste or needs: /// <summary> /// create a general class for SqlHelper database access, complete all operations on the database // </summary> public class SqlHelper {// define the database connection string private static readonly string connectionString = ConfigurationManager. connectionStrings ["strConnectionString"]. connectionString; // <summary> // creation method, perform a non-query operation on the database /// </summary> /// <param name = "SQL"> SQL statement </param> /// <param name =" parameters "> input parameters Count </param> /// <returns> </returns> public static int ExecuteNonQuery (string SQL, params SqlParameter [] parameters) {using (SqlConnection con = new SqlConnection (connectionString) {con. open (); using (SqlCommand cmd = con. createCommand () {cmd. commandText = SQL; cmd. parameters. addRange (parameters); string str = SQL; return cmd. executeNonQuery () ;}}/// <summary> /// result of the query completion /// </summary> /// <Param name = "SQL"> SQL statement </param> /// <param name = "parameters"> input parameter array </param> /// <returns> </returns> public static int ExecuteScalar (string SQL, params SqlParameter [] parameters) {using (SqlConnection con = new SqlConnection (connectionString) {con. open (); using (SqlCommand cmd = con. createCommand () {cmd. commandText = SQL; cmd. parameters. addRange (parameters); return Convert. toInt32 (cmd. execu TeScalar ());}}} /// <summary> /// mainly performs the query operation /// </summary> /// <param name = "SQL"> executed SQL statement </param>/ // <param name = "parameters"> parameter array </param> // <returns> </returns> public static DataTable ExecuteDataTable (string SQL, params SqlParameter [] parameters) {using (SqlConnection con = new SqlConnection (connectionString) {con. open (); using (SqlCommand cmd = con. createCommand () {cmd. commandText = sq L; cmd. parameters. addRange (parameters); SqlDataAdapter adapter = new SqlDataAdapter (cmd); DataTable dt = new DataTable (); adapter. after a class such as Fill (dt); return dt ;}}} is created, other classes that need to access the database can be created according to their own needs, the operations for adding, deleting, modifying, and querying are completed. Use a piece of code for Demonstration: /// <summary> /// Brief description of NewsDALL /// </summary> public class NewsDALL {// insert public int AddNews (NewsModel model) to the database) {string SQL = "insert into News (name, author, time, content, sort, isdelete) values (@ name, @ author, @ time, @ content, @ sort, @ isdelete) "; int nResult = SqlHelper. executeNonQuery (SQL, new SqlParameter ("@ name", model. strNewsName), new SqlParameter ("@ author", model. strNewsAuthor), n Ew SqlParameter ("@ time", model. strAddTime), new SqlParameter ("@ content", model. strNewsContent), new SqlParameter ("@ sort", model. sort), new SqlParameter ("@ isdelete", model. isDelete1); return nResult;} // execute the database deletion operation public int DeleteNew (int id) {string SQL = "delete from News where id = @ id "; int nResult = SqlHelper. executeNonQuery (SQL, new SqlParameter ("@ id", id); return nResult;} // execute the database update pu Blic int UpdateNew (NewsModel model, int nID) {string SQL = "update News set name = @ name, time = @ time, content = @ content where id =" + nID; int nResult = SqlHelper. executeNonQuery (SQL, new SqlParameter ("@ name", model. strNewsName), new SqlParameter ("@ time", model. strAddTime), new SqlParameter ("@ content", model. strNewsContent); return nResult;} // execute the database query Operation public NewsModel GetNewsModel (int id) // declare the data from Number of News entries in the library {string SQL = "select * from News where id = @ id"; DataTable dt = SqlHelper. executeDataTable (SQL, new SqlParameter ("@ id", id); if (dt. rows. count <= 0) {return null;} else if (dt. rows. count = 1) {NewsModel newModel = new NewsModel (); DataRow dr = dt. rows [0]; newModel. strNewsName = dr ["name"]. toString (); newModel. strNewsAuthor = dr ["author"]. toString (); newModel. strAddTime = dr ["time"]. ToString (); newModel. strNewsContent = dr ["content"]. toString (); newModel. sort = (int) dr ["sort"]; return newModel;} else {throw new Exception ("Exception! ") ;}} This NewsDALL class is mainly used to perform various operations on the database for news. Of course, this is only part of this class, it mainly demonstrates how the NewsDALL class calls methods in the SqlHelper class to complete database operations. 3) The next step is the last layer and the business logic layer. The business logic layer mainly processes the relationship between the view layer and the database access layer. Of course, you can also directly call the database access layer at the view layer, but the complexity of the relationship may increase. Therefore, the predecessors specially abstracted a business logic layer, after all the business logic relationships are processed at this layer, access the database access layer to perform data operations. (Of course, this is my understanding. If there is anything wrong, please correct me.) In my project, it seems that this layer is totally redundant, because you do not need to process too much business logic, you can directly access the database access layer at the view layer. Let's talk with the Code. Of course, this is still part of the NewsBLL class code: /// <summary> /// the business logic layer processes the direct relationship between the view layer and database access. /// </summary> public class NewsBLL {// adds the database. public static int AddNew (NewsModel model) {NewsDALL newDALL = new NewsDALL (); return newDALL. addNews (model) ;}// the public static int DeleteNew (int I) {NewsDALL newDALL = new NewsDALL (); return newDALL. deleteNew (I);} // returns the object public static NewsModel GetModel (int IntSort) {NewsModel model = new NewsModel (); if (intSort = 1) {model. strNewSort1 = ""; model. strNewSort2 = ""; model. strNewSort3 = "";} else if (intSort = 2) {model. strNewSort1 = "announcement notification"; model. strNewSort2 = ""; model. strNewSort3 = "";}.......... return model ;}} the next step is to use the access, business logic layer, and entity layer at the view layer to implement the required data operations. Use the code to describe the data. This code is mainly used to add the data: public void InsertData () {NewsModel newModel = new NewsModel (); newModel. strNewsName = this. textBox1.Text; newModel. strNewsAuthor = this. txtBoxAuthor. text; newModel. strAddTime = this. txtDate. text; newModel. strNewsContent = Server. htmlDecode (FCKeditor1.Value); newModel. sort = Convert. toInt32 (this. dropDownList2.SelectedValue. toString (); // NewsBLL newBLL = new NewsBLL (); Int nResult = NewsBLL. AddNew (newModel); if (nResult! = 0) {Response. Write ("<script> alert ('added successfully! ') </Script> ");} else {Response. Write (" <script> alert (' addition failed! ') </Script> ") ;}} I have sorted out the relationships between them. If you have any errors, please let me know, the three-layer architecture can be regarded as the basic framework for the development of a team project. On the basis of this framework, it can meet the needs of some design modes. Of course, it can meet the needs of module development. Summary: For my development project, there are still a lot of GAINS. I used to only know that there is a three-tier architecture. I also read books and wrote them according to other people's code, however, you cannot understand the true meaning. Advantages: ① It makes code reuse much higher, so you don't need to write the database code repeatedly on a page every time, instead of using a three-tier architecture, you only need to focus on the processing of business logic at the business logic layer and the compilation of SQL statements at the database access layer. ② Code is more concise and easy to use. Because different operations are placed on different layers, the Code logic is clearer. If comments are made, others can better understand the intent of the author. ③ The extended type is higher. You can write code at different layers as needed and then call it. ④ It is very beneficial for team development. Of course, the three-tier architecture is not just like this, or it will not become the basic framework for enterprise development. This is just an obvious advantage I have found in development. Let's share it with you. Disadvantages: ① The performance is definitely a little lower than the previous database operation code written directly on the corresponding page. However, this is completely acceptable. Moreover, for my current level, the code quality may still need to be improved and there is more room for optimization. ② In my project, I think the biggest waste is that I can directly access the database access layer at the view layer. because there are not many business logic to be processed, there is still code redundancy. Therefore, in the future, we need to follow the needs of our own projects to use them flexibly. It is not necessary to follow the regulations. This is just my opinion. please correct me for any errors. You are also welcome to communicate with me.

Related Article

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.