Introduction to delayed loading in C # (1) -- make good use of delegation

Source: Internet
Author: User

I heard it a long time ago."Delayed loading"I don't understand what it means. Now I know something about it. I want to write some articles as Reading Notes and record my thoughts. I hope this will help beginners, if a beginner or expert finds that the article is not well written or has better ideas and practices, please tell me. ^. The article is intended to be written in two or three articles. This is the first article.

In the layer-3 structure, we usually use one more"Model layer"The most important thing in this layer is to convert tables in the database (or other data sources, such as XML or a data format defined by yourself) into corresponding classes, for example, if there is an article table, there will be an article class at this layer. The attributes of the article class correspond to the columns of the article table. For example, the article title attribute corresponds to the article title column. Entity class and data tableOne-to-one correspondenceIs the simplest case. At this time, the entity class and entity class are respectivelyIndependent, with no reference relationship. However, almost every table in a database is associated (relational database). For example, in addition to the article table, there is also an article classification table, if every article must belong to a category, what is displayed in the database is that there is a foreign key field in the article table pointing to the primary key of the article category table, in C # code, it indicates that there is an attribute in the document class (Document category IDThrough this attribute, we can know the classification of the article, and query the database accurately by code to obtain an object of the article classification entity class, read the information about the document category.

The above process does not seem to have any problems at all. Sort out the ideas to read the database,Get an article object, read data from the database using the value of the document category ID in the Text object as the query condition, and obtain an article category objectOf course, database operations are typically encapsulated in the "data access layer. However, from the perspective of object-oriented, we hope that the article class contains the information of the article classification, and use code to represent the following two entity classes: "Article Classification" and "article:

C # code?
1234567891011121314151617181920 namespace Model{    // Document category entity class    public class ArticleCategory    {        public int CategoryID { get; set; }        public string CategoryName { get; set; }    }    // Article entity class    public class Article    {        public int ArticleID { get; set; }        public string Title { get; set; }        public string Cotnent{ get; set; }        public DateTime CreateTime { get; set; }        public int CategoryID { get; set; }        // Document category        public Model.ArticleCategory Category{ get; set; }    }}

From the code above, we can see that a model. articlecategory attribute category is displayed in the object class of the Article. What we want is to use this attribute to directly read the details of the category of the article. The problem arises. In the database access layer, after we read data from the database to instantiate an article object class objectWhen to assign a value to category?.

  • Select 1: Get the object of the document category through the category ID (categoryid attribute) immediately, then insert it to the "document category" attribute (category), and then return the article object. This method is a little bad, that is, you don't need to use the category attribute after getting the article object ...... Obviously, this approach is not good.
  • Option 2: read the document category when necessary, and assign a value to the category attribute of the document class object, ...... This is no different from the absence of this attribute.
  • Select 3: Read the database to obtain the document classification code in the get accessors of the category attribute. In this way, the code will not be called if the category attribute is not used, in this way, you will not access the database to get things. To avoid reading the database every time you access the category attribute, we add all the fields to the database. The Code obtained is as follows:
C # code?
12345678910111213141516 protected Model.ArticleCategory _category;public Model.ArticleCategory Category{    get    {        if(_category == null)        {            // Create an object for the document classification data access layer            Dal.ArticleCategory articleCategoryDal = new Dal.ArticleCategory();            // Obtain the document category            _category = articleCategoryDal.GetArticleCategoryByCategoryID(CategoryID);        }        return _category;    }    // Set accessors are not required}

At first glance, there seems to be no problem, but one thing to consider is that in the three-layer structure, data transmission relies on the "model layer", and the "model layer" is under the three layers. In other words, "Model layer" does not reference any layer in Layer 3The getarticlecategorybycategoryid in the above Code is obviously in the three layers, maybe in the "business logic layer" or "data access layer... this method is not good if it is referenced cyclically. How does one implement delayed loading of data in the category attribute in the document class? Sort out your ideas and analyze them step by step based on your needs:

At first glance, there seems to be no problem, but one thing to consider is that in a three-layer structure, data transmission relies on the "model layer", and the "model layer" is under the three layers. In other words, "model layer" does not reference any layer in Layer 3, while the getarticlecategorybycategoryid in the code above is obviously in Layer 3, either in the "business logic layer" or "data access layer ", so... this method is not good if it is referenced cyclically.
  • First, when a document object is obtained, the database is accessed only when the category attribute is read,Access is not allowed if you do not read
  • Second, when reading the category attribute of the same article Class ObjectAccess the database only once
  • Finally, in the get accesser of the category attribute, weThe method in layer-3 cannot be called (not directly displayed)

From another perspective, can we read data in the data access layer and initialize an article object?Give it a methodIf you want to obtain the information about your category (document category object), you can call this method. If you do not need to use this method, you will not call it to avoid reading the database by multiple links. "Give it a method", that is, pass the method to it! As a result, we can add a delegate to the document class. The signature of this delegate is the same as that of the "retrieve document category object through document category ID" method, this delegate is called in the get accesser of the category attribute, so that you can call the method in the get accesser to access the database, and naturally implement delayed loading! The code for modifying the object class is as follows:

C # code?
1234567891011121314151617181920212223242526272829303132333435363738394041 namespace Model{    // Document category entity class    public class ArticleCategory    {        public int CategoryID { get; set; }        public string CategoryName { get; set; }    }    // Article entity class    public class Article    {        public int ArticleID { get; set; }        public string Title { get; set; }        public string Cotnent{ get; set; }        public DateTime CreateTime { get; set; }        public int CategoryID { get; set; }                 // Document category        protected Model.ArticleCategory _category;        public Model.ArticleCategory Category        {            get            {                if (_category == null)                {                    if (CategoryLazyLoader != null)                    {                        _category = CategoryLazyLoader(CategoryID);                    }                    else                    {                        _category = null;                    }                }                return _category ;            }        }        // Document classification delayed loader (delegated)        public Func<int, Model.ArticleCategory> CategoryLazyLoader { get; set; }    }}

After reading the data from the database and creating an article-class object, we can assign a value to categorylazyloader! The methods for getting an article in the article data category are roughly as follows:

C # code?
123456789101112 // Obtain the object of the Object Class Based on the Article IDpublic Model.Article GetArticleById(int articleId){    // Retrieve data from the database, get a daterow or daterader, and initialize an object of the article object class.    Model.Article article = ... // "..." Is the code --!    // Create a document category Data Access Object    Dal.ArticleCategory articleCategory = new Dal.ArticleCategory();    // Specify the delayed loading delegate    article.CategoryLazyLoader = articleCategory.GetArticleCategoryById;    // Return the object of the article    return article;}

The category attribute in the object class obtained through the above method implements delayed loading!
The article is not short, but it is very simple to say. When I think about it, there is almost no content. One sentence is to use the delegate to get a method for retrieving the document category in advance, call the delegate to return the result in the get selector of the document category attribute. Okay. Tell the colleague responsible for writing the UI-Layer Code and call the method of the business logic layer to obtain the Object Class Object of the article ,! You have already added the article classification to the encapsulation, and you don't have to worry about how to implement the delayed loading. Just use it! This is why this person used it. There is a delegate in the object class Object of the article... delegate !!! Why !!!??? What do you mean! ### ¥ % # ¥ ...... % ¥ &...... % & # ¥ @! #

I wrote it here first. In the next article, I will talk about how to hide this delegate. I think that the students who learn about delayed loading should also come up with methods... (wipe! Toothache ~~~ Not powerful. 2011 ~~~~~~)

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.