Visual Studio "Whidbey" object space first
Explore the object / relationship mapping framework in the .NET environment - the characteristics of the object space
original:
Dino Espositowintelle
February 2004
translation:
Liu Haidong
2004-9-20
Applicable to:
Microsoft® Visual Studio® Code-named "Whidbey" Microsoft® ADO.NET Microsoft® SQL ServerTM 2000 SQL LANGUAGE
Abstract: Object space is the most interesting new feature in Microsoft VS, code whidbey. It is an object / relational mapping tool that is fully integrated with Microsoft ADO.NET and Microsoft .NET technology, object space in your business and physical library There is an abstraction layer between the medium original data. You only consider the object to be used by the design program, and the object space is responsible for reading and writing data from the data source by using the SQL statement.
Tip: Whidbey offers preview code at Microsoft 2003.10 Development Assembly.
content:
basic introduction
Object space overview
From the table mapped to classes
Get data object
Persistent layer change
Cooperate with object maps
Delay loading
Benefits of object space
basic introduction
When designing the data access layer (DAL) of the design .NET program, it is usually established by two options to establish a two-way interaction between the business representation layer and the DAL yourself. The first choice is to write a class from the ADO.NET object. And read data. The second option is to abstract the underlying table with a class, then add logical and program characteristics as needed. In both cases, the program is responsible for the transmission of structured data between layers, and uses SQL instructions read and write data.
In the former case, the main code is to bind the fields in the table with the element interface - it is very convenient to write .NET program. This is the biggest shortcoming is to write a lot of SQL. The statement is to process the data. If the size of the program increases, it will become very complicated and difficult to maintain, and the design of this program is data-centered.
Choosing more abstract and object-oriented don't completely get rid of this situation. Object-oriented models make you have a strong business logic layer, but you also need to have a layer of complex to persist objects to storage media. And this additional layer must be stored with storage The syntax of the medium is completely separated.
The object-oriented design is elegant and tidy, but it takes a lot of time to achieve it. NETROTECTURY. Nonworcening this, when a large program is closely related to management, hierarchical data and objective terms are very helpful. And this is often a unique way you can successfully complete the project. Because of this, the object relationship mapping (O / RM) tool has been a long time, and many suppliers have this technology.
An O / RM system allows you to persist in a specified storage medium. So you need an O / RM system to help you persistent objects, but you don't need to create an object to use this O / RM system You only define how objects are mapped with physical tables and fields, by O / RM to query and update data in the table.
Objectspaces
Object space is an O / RM framework integrated in whidbey. It provides a class to handle read and write operations for SQL Server 2000 and SQL Server Yukon data. The object space engine converts object queries to the table query and put The modification of the attribute in the object is converted to the modification of the table. Returns the data acquired will be converted into .NET class, the following figure is a probably described object space
Figure 1: Overall architecture based on object space
Through design, business rules describe the program logic and control the interaction between various entities in the problem domain. Business rules will form some objects with specific commercial entities, such as customers, orders, invoices, etc., not just some Data sets and tables.
The object space allows developers to focus on commercial entities, which are designed by reasonable objects instead of a set of data streams. The object space requires a simple map class and data table. After the object space engine processes the data source operation and take you from Details of the operation. Therefore, you can make a program with flexible, reusable and expandable objects. At the same time, you can store the data in the relational database.
The architecture of the object space is located between the program logic and the data source, which enables the developer to manage the data without the need to understand too much knowledge on the physical storage of the data. By using the object space, you don't need to write the data and read data. SQL code.
Map table to class
The root class of the object space architecture is ObjectSpace. ObjectSpace class handles information interact with the data source and manages the actions of the query and obtains the data source. The object space is responsible for persistent objects to the data table and instantiate the results of the query. To make the object space action You need to map the structure to the ADO.NET connection object. The mapping mode can be a static resource such as an XML file, or dynamically established through the interface of the mapchema object. Mappingschema object determines which fields and tables are used for persistent object data, and Data should be read from the fields and tables. The following code snippet demonstrates how to instantiate an object space:
DIM CONN As SqlConnection = New SqlConnection (ConnString)
DIM OS As Objectspace = New ObjectSpace ("MyMappings.xml", Conn)
The connection object here is just a normal data connection, which contains parameters connected to an SQL Server instance.
Mapping mode is divided into 3 parts: Relationship mode definition (RSD), object mode definition (OSD), and mapping mode, it is responsible for connecting the front two mode. For convenience, you can put each mode into a separate XML file. In this case, only the mapping mode file must be passed to the creation method of the object space. Relationship mode and object mode are referenced in the mapping mode.
The mapping mode file shown in the list below is bound to a relational mode file (RSD.xml) containing the NothWind database table and an object mode file (OSD.xml).
XMLns: m = "http://schemas.microsoft.com/data/2002/09/28/mapping"> Direction = "Source"> m: DataSource> m: DataSource> m: datasources> m: map> m: mappings> m: mappingschema> Define the data sheet and a binding relationship of the data table and a .NET class in The relationship mode of the source data is defined as follows: XMLns: rsd = "http://schemas.microsoft.com/data/2002/09/28/RSD"> XMLns: r = "http://schemas.microsoft.com/data/2002/09/28/RSD"> Precision = "40" /> SQLTYPE = "nvarchar" precision = "30" /> Precision = "24" /> rsd: columns> rsd: primarykey> rsd: constraints> rsd: table> rsd: tables> r: schema> rsd: database> As you can see, this relationship mode only selects a small number of columns in the Customer table, and the primary key is included in the list of columns. Object mode definition files are as follows: XMLns: osd = "http://schemas.microsoft.com/data/.../persistenceschema"> osd: Class> osd: classes> oscum: extendedObjectschema> The File Describes a class like the one shown below. Namespace Samples Public Class Customer Public ID as string Public Name As String Public Company As String Public Phone as string END CLASS End Namespace In summary, mapping information indicates how object spaces serialize and deactivate between the data of the Samples.Customer object with the Customer table. Below we will demonstrate how to write data with Customer class, before you start, see which methods defined in ObjectClass: method description BeGintransaction Start a transaction of a data source Commit Submit the current transaction in the data source GetObject Returns the object of the specified type in the query string from the data source GetObjectReader Returns the target stream of the specified type in the query string from the data source GetObjectset Returns the object collection of the specified type in the query string from the data source Markfordeletion The specified object is deleted, the object record (and associated data record) in the data source will be deleted after the PersistChanges Marks is executed Persistchanges Association operation, delete, update, and delete update to the data source RESYNC Re-read the value from the database and refresh the status Rollback Current transaction in rollback data source StartTracking The mark object is a persistent object, starting to prepare I / O operations for the data source These methods can be divided into three categories - transactions, read, written. BeGintransaction, commit, rollback are all transaction-related methods. The method of reading is RESYNC, GetObject, GetObjectRectReader, and getObjectSet. These getxxx methods returns entity objects for mapping classes. These methods differ in the number of objects returned to the number of objects. GetObject and getObjectSet will call GetObjectReader to read data internally. . GetObject only returns the first object from the result set, if there are multiple data objects to return to the exception. GetObjectReader returns the stream of objects, an ObjectReader object is very similar to the DataReader in ADO.NET, returns to the data, keeps the connection, and then shut down immediately after turning off the ObjectReader. GetObjectSet Returns a collection of non-connected data objects, the return type is ObjectSet, similar to the DataAPter's Fill method. How is the mapping of the program object and the data source? Let's take a look at the parameters of these methods. Function GetObject (t as type, query as string) AS Object Function GetObjectReader (T as Type, Query As String) As ObjectReader Function GetObjectSet (t as type, query as string) AS ObjectSet The first parameter TYPE of all functions is the class name corresponding to the data object. Here is the sample code segment: DIM Dataset As Objectset DataSet = Os.GetObjectSet (Gettype (Customer), "ID = 'Alfki'") According to the query condition string, the query object for the data source is generated, and the target stream of the result set will be obtained first in GetObjectSet. After processing, different rows are loaded into different objects, and then returns a collection of objects and turn off the database connection. It is important to indicate that all objects retrieved by the getxxx method are automatically tracked by the object space engine. No need to call the StartTracking method to attach them to the object space engine. The RESYNC method can take one or a set of objects and update their data in time by running a new query. The method related to writing is StartTracking, MarkFordeletion and PersistChanges. STARTTRACKING lays the object as a persistent object. When this method is called, the object is given a status value and is added to the environment variable of the object space system to track its data change. The object is tracked with the statute of DATAROW in ADO.NET. When the PersistChanges method is called, the object indicates whether the object should be added, deleted or updated to the data source. Below the following example how to use these methods under the architecture of the object space: Getting data Objects In order to use object space in your Whidbey program, you need to reference two files, System.Data.ObjectSpaces and System.Data.sqlxml. If it is convenient, you can also import the System.Data.ObjectSpaces name space directly in the source code. Imports System.Data.Objectspaces After copying the mode files used in the program to the same directory with the program execution file: DIM Connstring as string = "..." DIM CONN As New SqlConnection (ConnString) DIM OS AS New ObjectSpace ("Map.xml", CONN) DIM Query As New ObjectQuery (GetType (Customer), "ID = 'Alfki'") Dim Reader as ObjectReader = Os.GetObjectReader (Query) For Each C As Customer in Reader Custid.text = C.ID Custname.text = c.name Custcompany.text = C.Company Custphone.text = C.Phone NEXT Reader.close () The above is a Windows Form program code snippet, which shows a window with text box - Customer Number, Name, Company and Phone Number. The running query is an instance of an ObjectQuery class. This class's creation method requires the type of object and a query string. The type of object specifies the business object with the data source exchange information. It must be explained that the query string should be written according to the name of the persistent object attribute, not the field name in the database. The above query string returns the ID attribute equal to the client object of the Alfki. A new language for querying objects called OPath, which is similar to XPath so that you can write query statements with object-oriented syntax. This query object is passed to the GetObjectReader method and returns a stream-based ObjectReader object. The content of an ObjectReader can be used to read the returned customer object with FOR .... For Each C As Customer in Reader 'Process Information Here NEXT Since the data in each line in the database is mapped to the user-defined class instance, the element that binds the properties of the class to the user interface is a dish. The following figure shows the effect of the presentation code in PersiSting Changes The PersistChanges method is responsible for writing object space monitoring objects back to the database. The object retrieved with the getxxx method has been automatically tracked, but what about the new object? The following code demonstrates how to add an object to the system: DIM C As New Customer C.Name = "Belinda Newman" C.Company = "LITWARE, Inc." C.Phone = "(425) 707-9790" C.FAX = "(425) 707-9799" Os.StartTracking (C, InitialState.Inserted) Create and fill a new object here, then use the startTracking method to add it to the object space. Calling this method requires an initial status value to indicate that the object is new or already existing. INITAILSTATE has only two value inserted and unchanged. When the PersistChange method is called, the object that is labeled for INSERTED will add a corresponding record in the database. Os.PersistChanges (C) Note that there is a FAX attribute in the object here, and does not map the field of the playing in the previous mode file. (What is the result, the author does not clearly explain it) Master from object Object space can also handle complex hierarchical primary slaves, common than one-to-many relationship between customers and orders. Assume that the improved customer category is as follows: Public Class Customer Public ID as string Public Name As String Public Company As String Public Phone as string Public Fax As String Public Orders as arraylist = new arraylist () END CLASS The new order property will contain the customer's order, read the code of the customer and order as follows: Dim Reader As ObjectReader Dim oq as new ObjectQuery (Gettype (Customer), "ID = 'Alfki'", "Orders") Reader = Os.GetObjectReader (OQ) For Each C As Customer in Reader OutputCustomer (C) For Each O as Order in C.OrDERS Outputorder (O) NEXT NEXT Reader.close () Two important changes have been hidden in the above code, one is a mapping mode between customers and orders, one is the creation parameters of ObjectQuery. In this example, ObjectQuery creates three parameters: Returned object type, OPath query string and range string. The range string is a set of associated objects with comma. The value specified here is ORDERS to ensure that orders related to customers will be returned. In the mapping mode file used by the program, the Fromvariable = "Customers" TOVARIABLE = "ORDERS"> m: Relationship> m: DataSource> Customers and orders are defined in Add new nodes ParentClass = "Customer" ParentMember = "Orders" ChildClass = "Order" childmember = "Customer" /> osd: ObjectRelationshipsHips> Delay loading In order to improve memory consumption in the main slave relationship, the object space provides a feature "delay load". It can be used in a pair and one-to-one, its design idea is that the object data is only loaded when it is requested. Where ObjectList provides a pair of multi-object delay load functions, ObjectHolder provides a pair of delayed loads. To access the actual object, ObjectList is through its InnerList property, ObjectHolder is through InnerObject, and their types are Object. In order to access objects of delayed loading by mandatory types, they can be encapsulated with a specified type. In the following code, the order attribute is in ObjectList, but the INNERLIST is mapped to its actual type ORDERLIST when accessing properties. Public Class Customer Private m_orders as objectlist = new ObjectList () Public Property Orders as OrderList Get Return m_orders.innerList END GET Set (ByVal Value As OrderList) m_orders = value End set End Property : END CLASS In order to make the delay loading attribute to object space correctly, you can use the lazyload attribute in the OSD mapping file. Moreover, OSD needs to establish a relationship, the member attribute is private, not public. ChildClass = "Order" childmember = "m_orders" /> Delay the loaded properties, only load data only when it is accessed by the code in the program. Moreover, the object space does not imply the refreshing data of the delay, but you can force the data with FETCH. Object space Although there is still far from the ultimate completion, the object space is undoubtedly the most interesting new features in Whidbey. It is an O / R mapping tool that is fully integrated from ADO.NET and .NET technology. It adds an abstraction layer in your application to isolate the business logic layer and physical data access layer. And the programming model of the object space is very close to ADO.NET, which is conducive to the learning and master of .NET programmers. Object space, as well as other similar class library frameworks, will bring partial load to the program and require developers to have a certain understanding of the programming model. Today, it is believed that the subject space needs to improve the following: The debugging tracking system is less efficient, lacking auxiliary mapping tool, the quality of SQL statements remains, and low load performance. By the way, Visual Studio Whidbey is still a very far-release product, and has not yet entered the stage of public testing. It's only just beginning, let us wait and see this technology. About author Dino Exposito is a lecturer and consultant in Rome, Italy, one of the members of the Wintellect team. Focus on ASP.NET and ADO.NET technology, most of the time is used in Europe and the United States. In addition, it is also responsible for the production of Wintelle's ASP.NET and ADO.NET courseware, writing the "frontier" column in MSDN magazine.