Learning PetShop3.0 (6) entity model

Source: Internet
Author: User

Do you still remember how users collect information during registration? The following statements:

//......
AddressInfo address = addr. Address;
//.....
AccountInfo accountInfo = new AccountInfo (userId, password, email, address, language, favCategory, showFavorites, showBanners );
//.....
CcountController. CreateAccount (accountInfo)

Both AddressInfo and AccountInfo are thin object classes, and the entire program uses this model to complete information transmission. These classes are defined in the Model component. It should be one of the most important components in petshop3.0.
Model: A thin data class that transmits data between layers of applications. These are implemented using the C # class, and each field is made public in the form of attributes. Each class is marked as "serializable" to enable inter-process transmission.
. Net is object-oriented. We all know that what can be done in specific implementation? In short, I completely do not understand. However, after reading the application of the Model component in petshop3.0, I have gained a long experience.
There is always a certain amount of information in the program that can be classified into one type, such as product information, user information ...... For user information, there should be specific information such as user name, password, address, phone number, personal interests, etc. In petshop3.0, these can be regarded as an entity, and the information in the entity is an attribute of this category. In this case, information such as the address and phone number can be separately classified as an entity, because they describe personal information and are variable (the description is not very accurate and may be incorrect ). So we can see that petshop3.0 converts this information into an AddressInfo object, and this object becomes an attribute of the AccountInfo object. In specific applications, these entities are used as a whole, because you cannot cut a person, right? From the perspective of c #, these are all types and can be seen as user-defined types. Therefore, we can see that the AddressUI user control uses AddressInfo as a property to make public.
The object Model runs through petshop3.0. On the surface, almost every layer references the Model component. In the case of users, when the presentation layer collects data, the user-filled information is collected as an entity, after completion, the user interface processing component will send the information entity as a parameter to the business logic component, and the business logic component will then send the information entity as a parameter to the data processing component through the factory. Here, the final processing is done, submitting to the database or returning an error.
In the whole process, there is no individual transfer of value types. The benefits of doing so are obvious, making logical operations more transparent and easy to understand, facilitating the construction of complex system models, and encapsulating information that does not need to be disclosed to the program.
This type of code is everywhere. An obvious example is CartItemInfo. This entity model expresses the items placed in the shopping cart. This entity is not stored in the database and exists in the process. The existence of this entity greatly simplifies the composition of the abstract entity of the shopping cart.
In fact, there is no Cart entity in the root of the Model component. The implementation of Cart is completed by the BLL component. This Cart is not the same as the thin entity class above, but another entity model, because it not only contains information as the entity itself, but also has its own behavior. According to the call on msdn, this is a business entity with CRUD behavior ". We can regard this Cart as an intelligent robot. He will pick his own goods and give information about the current car.
Compare Cart and CartItemInfo by using the class diagram.



Cartiteminfo only has attributes, while cart includes attributes and methods.
It should be noted that the cart belongs to the business logic component because it is used to execute its behavior and its main attribute is an indexer, use this to obtain cartiteminfo.

Finally, let's take a look at the cartiteminfo code to understand the basic structure of this model.

/// <Summary>
/// Business entity used to model items in a shopping cart
/// </Summary>
[Serializable]
Public class cartiteminfo {

Private const string Yes = "yes ";
Private const string NO = "no ";

// Internal member variables
Private int _ quantity = 1;
Private bool _ instock = false;
Private string _ Itemid = NULL;
Private string _ name;
Private decimal _ price;

/// <Summary>
/// Default constructor
/// </Summary>
/// <Param name = "itemId"> Every cart item requires an itemId </param>
Public CartItemInfo (string itemId ){
This. _ itemId = itemId;
}

/// <Summary>
/// Constructor with specified initial values
/// </Summary>
/// <Param name = "itemId"> Id of item to add to cart </param>
/// <Param name = "name"> Name of item </param>
/// <Param name = "inStock"> Is the item in stock </param>
/// <Param name = "qty"> Quantity to purchase </param>
/// <Param name = "price"> Price of item </param>
Public CartItemInfo (string itemId, string name, bool inStock, int qty, decimal price ){

This. _ itemId = itemId;
This. _ name = name;
This. _ quantity = qty;
This. _ price = price;
This. _ inStock = inStock;
}

// Properties
Public int Quantity {
Get {return _ quantity ;}
Set {_ quantity = value ;}
}

Public bool InStock {
Get {return _ inStock ;}
Set {_ inStock = value ;}
}

Public decimal Subtotal {
Get {return (decimal) (this. _ quantity * this. _ price );}
}

Public string ItemId {
Get {return _ itemId ;}
}

Public string Name {
Get {return _ name ;}
}

Public decimal Price {
Get {return _ price ;}
}
}

The following are some information about business entities on msdn. By the way, it turns around :)
---- Original address ------

Define custom business entity components
The user-defined class of a business entity usually contains the following members:

A special field used to cache data of a business entity locally. These fields save a snapshot of the database data when the data access logic component retrieves data from the database.
It is used to access the state of an object and to access the subset of data within the object and the Public attributes of the hierarchy. These attributes can have the same names as database columns, but they are not an absolute requirement. You can select an attribute name based on your application needs, without using the name in the database.
Methods and attributes used to use data in the Entity component for localization.
Events used to notify the internal status change of the entity component.
Figure 9 shows how to use a custom object class. Note: The entity class does not know the data access logic component or basic database. All database access is performed by the data access logic component to centralize data access policies and business logic. In addition, the method for transmitting Business Entity Data between layers is not directly related to the format used to represent the business entity. For example, you can locally represent a business entity as an object, another method (such as scalar value or XML) is used to transmit Business Entity Data to other layers.

Figure 9: Role of a custom business entity component (click a thumbnail to view a large image)

Suggestions for customizing business entity components
When implementing a custom object component, consider the following suggestions:

Select a structure or a class. For simple business entities that do not contain hierarchical data or collections, you can consider defining a structure to represent business entities. For complex business entities or business entities that require inheritance, entities can be defined as classes. For more information about the types of Structures and Classes, see Structures and Classes.
The status of the business entity. For simple values such as numbers and strings, you can use the equivalent. NET data type to define fields. For code examples that describe how to define custom entities, see how to define business entity components in the appendix.
Indicates the subset and hierarchy in the Custom business entity component. There are two methods to indicate the subset and hierarchy of data in a custom object:
. NET set (for example, ArrayList ).. The. NET collection class provides a convenient programming model for a set with adjustable sizes, and provides built-in support for binding data to user interface controls.
DataSet. DataSet is suitable for storing data sets and hierarchies from relational databases or XML files. In addition, DataSet should be preferred if you want to filter, sort, or bind sub-sets.
For code examples that describe how to represent the set and hierarchy of data in a custom object, see how to represent the set and hierarchy of data in a custom object in the appendix.

Supports data binding on the client on the user interface. If a custom object is to be used on the user interface and you want to use automatic data binding, you may need to bind data in the custom object. Consider the following solutions:
Data Binding in Windows Forms. You can bind the data of an object instance to a control without the need to bind data to a custom object. You can also bind an array or. NET set of objects.
Data Binding in Web forms. If you do not implement the IBindingList interface, you cannot bind the data of the entity instance to the control in the Web form. However, if you only want to bind a set, you can use an array or. NET set instead of implementing the IBindingList interface in a custom object.
For sample code that describes how to bind a custom object to a user interface control, see how to bind a business entity component to a user interface control in the appendix.

Events that expose internal data changes. A wide range of client user interfaces are available for public events, because they allow data to be refreshed wherever it is displayed. The event should be based only on the internal status, rather than on data changes on the server. For code examples that describe how to expose events in the Custom entity class, see how to expose events in the business entity component in the appendix.
Enable service entity serialization. The service entity can be serialized to maintain the state of the business entity in the intermediate state without database interaction. This facilitates the development of offline applications and the design of complex user interface processes, that is, business data is not affected before completion. There are two types of serialization:
Use the XmlSerializer class for XML serialization. If you only need to serialize public fields and public read/write attributes into XML, you can use XML serialization. Note: If the Business Entity Data is returned from the Web service, the object will be automatically serialized to XML through XML serialization.
You can perform XML serialization on business entities without any additional code in the entities. However, only the public fields and public read/write attributes of the object are serialized as XML. Private fields, index generators, private attributes, read-only attributes, and object graphs are not serialized. You can use the property control result XML in the custom object. For more information about serializing a custom entity component to an XML format, see how to serialize a business entity component to an XML format in the appendix.

Format serialization using BinaryFormatter or SoapFormatter class. If you want to serialize all the public fields, private fields, and object graphs of an object, or you want to transfer an object component to a remote server, you can use format serialization.
The format class serializes all public and private fields and attributes of the object. BinaryFormatter serializes the object to binary format, and SoapFormatter serializes the object to SOAP format. The serialization using BinaryFormatter is faster than using SoapFormatter. To use any format class, you must mark the object class as the [Serializable] attribute. To explicitly control the serialization format, your class must also implement the ISerializable interface. For details about how to use format serialization, see how to serialize a business entity component to a binary format in the appendix and how to serialize a business entity component to a SOAP format.

Note: When a serialized object is restored, the default constructor is not called. This constraint is added to restore serialization for performance considerations.
Custom entities have the following advantages:

The code is easy to read. To access data in a custom object class, you can use methods and attributes of the type, as shown in the following code:
// Create a ProductDALC object
ProductDALC dalcProduct = new ProductDALC ();

// Use this ProductDALC object to create and fill in a ProductEntity object.
// This Code assumes that the ProductDALC class has a method named GetProduct,
// This method uses the Product ID as the parameter (21 in this example) and returns
// The ProductEntity object that contains all the data of the product.
ProductEntity aProduct = dalcProduct. GetProduct (21 );

// Change the product name of the product
AProduct. ProductName = "Roasted Coffee Beans ";

In the preceding example, a product is an instance of a custom object class named productentity. The productdalc class has a method named getproduct, which creates a productentity object, fills in data of a specific product to this object, and then returns the productentity object. You can use properties such as productname to access data in the productentity object and call methods to operate on the object.

Encapsulation. Custom entities can contain methods to encapsulate simple business rules. These methods operate on Business Entity Data cached in the Entity component, rather than accessing real-time data in the database. Consider the following example:
// Call a method defined in the productentity class.
Aproduct. increaseunitpriceby (1.50 );

In the preceding example, the application is called to call a method named increaseunitpriceby on the productentity object. This change is not permanent until the application calls the corresponding method to the productdalc object and saves the productentity object to the database.

Build a model for a complex system. When constructing a model with complex domain problems (there are many interactions between different business entities), you can define custom entity classes to hide the complexity behind well-defined class interfaces.
Local verification. Custom object classes can perform simple verification tests in their property accessors to detect invalid Business Entity Data. For more information, see how to verify data in the property accessors of the business entity component.
Special Field. You can hide information that you do not want to publish to the caller.
The disadvantages of defining a custom object are as follows:

A collection of business entities. A custom entity represents a single business entity rather than a collection of business entities. To save multiple business entities, the calling application must create an array or a. NET collection.
Serialization. You must implement your own serialization mechanism in the custom object. You can use attributes to control the serialization method of object components, or implement the ISerializable interface to control serialization.
Complex relationships and hierarchies in business entities. You must implement your own relationship and hierarchical representation in business entity components. As described above, DataSet is usually the easiest way to achieve this.
Search and sort data. You must define your own mechanism to support searching and sorting objects. For example, you can implement the IComparable interface to save an object component in a SortedList set or Hashtable set.
Deployment. You must deploy an Assembly that contains a custom object on all physical layers.
Supports Enterprise Service (COM +) clients. If a custom object will be used by the COM + client, a strict name must be provided for the Assembly containing the object and must be registered on the client computer. Generally, this Assembly is installed in the global assembly cache.
Scalability problems. If you have modified the database architecture, you may need to modify the custom object class and redeploy the assembly.
Define custom business entity components with CRUD Behavior
When defining a custom object, you can provide methods to fully encapsulate crud operations on the basic data access logic component. This is a traditional object-oriented method and may be suitable for complex object domains. The client application no longer directly accesses the data access logic component class. Instead, it creates an object component and calls the crud method for this object component. These methods call basic data access logic components.

Figure 10 shows the role of a custom object class with crud behavior.


Figure 10: Role of a custom business entity component with crud behavior (click a thumbnail to view a large image)

Custom object classes with crud behaviors have the following advantages:

Encapsulation. Custom entities can encapsulate operations defined by the basic data access logic component.
The interface with the caller. The caller must process only one interface to maintain the Business Entity Data. You do not have to directly access the data access logic component.
Special Field. You can hide information that you do not want to publish to the caller.
The disadvantages of defining a custom object class with crud behavior are as follows:

Process a set of business entities. The methods in the custom object belong to a single business entity instance. To support business entity sets, you can define static methods to read or return an array or an entity component set.
Long development time. Traditional object-oriented methods usually require more design and development work than existing objects (such as dataset.

Author: Mike

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.