l Introduction The "efficiency" two words have been a topic of many programmers from the top of the "efficiency" from the day. Net. Net. Whether it is from the development model (Cross Language), the system framework (.NET Framework), it is not a victorious person who has a variety of easy tools (VS.NET). At the same time, on the other hand, whether .NET can truly compete for the heavy responsibility of enterprise application (Enterprise Application), but still arguing, it is very different. Generally speaking, there are many aspects, such as security, performance, scalability, ease of use. In this article, the author is more willing to discuss the relevant technologies of the data access layer under the .NET, which may be a wide focus on the sensitive topic of the N-Tier Architecture, and for most For developers, this may also be the most depressed part of the project, or even the most controversial part. In the following discussion, in order to unify, the author temporarily refers to the data access layer is referred to as DAL (Data Access Layer). l After analyzing the problem, it is not difficult to find that DAL is afraid, not for the problem of technical itself, even in contrast, many developers think this is one of the most technical content (on the author In view of the size of the project, the development time of this layer is generally short, and many developers are unwilling to bear the "bitterness"), but the architecture needs or certain ideas (such as: Dal and DAL) have only joined this The so-called fourth layer (traditional three-layer architecture has not proposed DAL thinking). DAL's proposal, it is indeed a huge challenge to the traditional architectural model. The purpose of joining is also hoping to borrow him further increase productivity. In this mode, ideal is: Most developers get rid of DBA suffering, or thoroughly Direct relationship with the database, SQL pain will go away from us, the entire OO world is quiet. However, ideal is ideally, it is necessary to pass the project inspection. Next, the author attempts to analyze a relatively popular and representative solution to see if there are some valuable conclusions, and provide some reference for us to design and implement DAL in the future. U ado.net First, mention the DAL under .NET, immediately reflecting the eye blind is ADO.NET. Yes, almost all DAL solutions (please allow the author to use Solution rather than framework) must have been developed from it, which is not selected, which is also a .NET feature (compare J2EE). Exclude business factors and CLR itself, ADO.NET truly brought us, worth mentioning, Dataset (for authors), using more DataTable and DataView). From Microsoft's early memory database (Memory Database), I'm asked to come to Today's Dataset, and the songs of these songs can be exhausted. In short, there is a little bit of certainty, it is a DataSet. Dal under NET can be like today, and the ideas of everyone can be more open. Duwamish has a lot of good SAMPLE, the most classic universal development package for Microsoft's strong recommendation: duwamish.
For friends who want to learn .NET DAL, this is a good starting point. In this regard, you can refer to "9CBS development masters, 2003.11", this article is not described later. The author uses the Duwamish program in a project that has participated in, when it is limited to the time, feeling this is a good reference, not doing in-depth analysis, start designing. Now I recall, I found still there are still many shortcomings. For a simple example, Cache Management is not considered in the Duwamish scheme, and this is a problem that you have to consider for enterprise applications; on the other hand, although DUWAMISH says goodbye to the SQL statement (all adopted storage Process implementation), but database traces are still very obvious, such as: definition of certain field names, definition of association table name, etc. There is also a very headache problem that is reflected in the development process. At first, those relatively simple data sheets are more easy to implement, and when some of the DAL engineers containing the interrelated data sheets, we have done it later, almost done DBA has been done in the database modeling. Work, only, this time to change the database script C # implementation (or said: replacing the database structure with a Dataset with OO featured on the surface. It may, Duwamish's implementation is more classic, but in practical applications, it is sometimes not meant to be Best Practice. Take our project, although successful delivery, no matter from the model multiplexing angle, it is still a successful development efficiency. Set of popular words: In fact, we can do better! Another DAL implementation worth a reference on PETSHOPADO.NET is a famous PetShop. Of course, similar to duwamish, the famous arrogance is not necessarily practical. Although PETSHOP makes up for the shortcomings of duwamish, for example, the multi-database reservoirs are supported by Factory, introducing the Cache mechanism, providing more convenient SQL Helper, but also brought other problems. Among them, the most troublesome is the introduction of the SQL statement, but also different SQL statements stored in different data deposits (mainly SQL Server and Oracle parameters). On the other hand, although PETSHOP does not use the DataSet in a more concise ordinary entity object (MODEL), but it still converts DataReader's results to the list collection of the entity object, in this sense, It can be described as refined to change the medicine. Even in some occasions, for example: data is required to filter, or navigate between the master-slave data, but more inconvenient (at this time, simple Collection or List can not meet the demand, DBA and DAL developers can only provide Other methods to achieve the goal). From the above two examples, we can see that even in the Microsoft's development team, there is no consistency on the issue of DAL. More details in this regard, interested friends can refer to the following article: http://www.microsoft.com/china/community/column/67.mspx. Two solutions to the actual combat, let us see their respective advantages and shortcomings, and the complex environment of enterprise applications is unlikely to solve all the problems, so It can be specifically analyzed according to the specific situation.
The author has participated in the development of a (.NET) large outsourcing project, fortunately, his DAL is designed, deeply shocked, here to discuss together with friends. Take the Northwind database with SQL Server as an example, as follows, a para-based call code (the author has made some names on some name): // Return to its titleboemp = new Employeedal () according to EMPLOYEEID; Boemp.keys ["EMP_ID" ] = 1; // Note: The actual field name is: employeeidboemp.select (); string strTITE = Boemp ["EMP_TITLE"]; // Note: The actual field name is: title ... / / According to City, return all eligible conditions EMPLOYEEBOEMP = New Employeedal (); Boemp.keys ["EMP_CITY"] = "Seattle"; Boemp.Select (); // Note: This method is exactly the same DataTable DTEMP = Boemp.Table; if the object is created (You can use Object Pooling or Cached Object) and after the call, the actual code is only two lines! More surprisingly, the above Employeedal class does not have any true realization code, just declare the class name, then inherited from a general base class! ! The most elegant place is not here. In fact, even in that base class, you can't see the gang dispute between SqlConnection or Oracleadapter. I believe everyone also guess, it's right, it is borrowed from the implementation of PETSHOP, using the Factory mode to ensure that DAL can apply to different data sets. However, this implementation is still very different from PETSHOP: At least, it does not produce different SQL statements, and there is no different parameter call mode (SQL Server usually uses "@" symbols, Oracle general use ":": " Symbols), all gangstere the colleagues! Among them, it is of course benefiting from the implementation skills of Factory, but more important factors are still exempt from design. In fact, in the .NET Framework, this design of the cornerstone is provided, which is white, which is the interface in System.Data (such as IDBConnection, iDataAdapter, etc.). Based on such a design, we will no longer need to provide different data access to different data deposits for each DAL class. For example: In PETSHOP, the order data needs to implement the Order class, which is natural, the system implements the Order class for SQL Server and Oracle, respectively, and operates with the methods provided by Different Provider (SqlClient, OracleClient). When actual calls, PetShop dynamically create a real ORDER class through the Factory mode and activate the corresponding method, a scheme for different data deposits. In fact, PETSHOP has been more flexible. If you can save the "writing of different Order classes", you really send to the Buddha to get J.
And all of these features, in this project participated in the project, it has been fully available! As for "Employeedal (of course, including all of all DAL classes), there is no real implementation code.", Only playing a small configuration skill: Will different DAL classes with related stored procedure (please note: not Table or VIEW) Store in the XML file according to NameSpace. You may have seen it, in theory, even only one DAL class can complete all the above work! However, in practice, different DAL classes may still have some subtle differences on data processing (such as data check, format conversion, etc.). In general, in such a large project, it is impossible to ask all developers (except DBA, Dal Framework Developer to learn about the all aspect of ADO.NET, although the author has research, but in this project, Only two classes from the end of the end: DataTable, DataView (even if transaction does not need to know)! Others ending ADO.NET, you have to mention the brothers between DataReader and DataSet. With the information you've seen, almost all recommendations are recommended to analyze the actual situation, and there are few very few very few of the individual habits. When studying ADO.NET, the author is also in such an idea, and repeatedly remembers those terms summarized on the information (just like learning Gof 23 in the year, almost fell like a flowing J), thinking that there is another day can also be in ADO The big exhibition of .NET. Unfortunately, the reality is not willing to have a few projects, regardless of the size of the size, it actually uses the DataSet solution! At this point, look back to see the most frequent PETSHOP project when learning ADO.NET, and two comparisons, this is a little bit. Simply put, PETSHOP uses this "curve saving country" way to implement data exchange: DataReader Get Data => Create Data Entity Class => Fill data entity class according to field type Plug data entity class => Add a data entity to the list class ( Only for occasions returning more than one data) (Supplement: Adopt data entity class or set class can be easier to implement Cache Manament, and ordinary DataReader is unable to meet this process with DataAdapter due to its data reading mode restrictions). Fill () The effect is similar, but only, DataAdPater automatically creates DataReader to obtain data in Fill (), then create DataTable (equivalent to the data entity class), and populates DATATABLE according to the field type, of course, if possible The records, DataTable can be handled, and there is no need to implement the list of operations. Maybe readers will have questions immediately: In this case, why does the data entity are needed in PETSHOP? There are still some differences.
First, the data entity class is a lightweight structure, which generally contains only the data field, no way of operation, which is better than DATATABLE or DATAROW, and it can be ignored when the amount of data is not large); on the other hand The operation of the data entity is relatively simple. It does not require developers to have any ADO.NET knowledge (in fact, it is not a problem, this is not a problem), and some attributes can be. However, according to the authors, these two does seem to be indiration to use the DataReader program, the reasons are listed below: (1) For occasions with large amounts of data, it can be used in batches. Similar to data paging effects of DataGrid; (2) For simple data, physical classes can also be credited, once related to associated data, it can only be written separately. And all of this, is very easy to handle in DataSet (for enterprise applications, most of the cases need to handle more complex data); (3) DataTable "Natural" supports data collection operation, such a characteristic ratio "collection Entity "mixed mode (PETSHOP) is more easier to control, and it is more natural; (4) The entity class needs to determine all data types when declaring, when data is filled, it is necessary to pay again to pay attention to the data type corresponding to the entity, and cannot be Silk error! In this regard, DataTable is very convenient and only one type is only a type of attention; (5) DataSet solutions can be very convenient to support serialization operations (such as remote, webservices), and the relationship with XML is more Intimate, this is also critical for interaction with other systems. It has been analyzed some technologies and programs, and believes that readers have some experience. On the occasion of this receipt, if it is necessary to provide a "sum of it" here, the author's suggestion is very clear: in enterprise-level application development, as much as possible using Dataset (DataTable / DataView) Cache Management Solution Program! In other development, only the DataReader is considered in the following four situations (for the author's experience, mostly using the DataReader are the second case): (1) The resource is more demanding, the resources here refer to memory And database connections; (2) Temples wishing to be customized when reading the database returns, for example, terminating processing immediately after reading a record, or performing a calculation operation when reading.
(Tip: This situation is similar to the SAX (Simple API for XML) technology in XML, there is no need to read all XML data at once; the opposite, DOM (DOCUMENT OBJECT MODEL) requires that all XML data must be loaded Can you start operation (MSXML4.0 has begun to allow only XML document section to start operation, this is a severity)!) (3) I only want to get the number of fields that return the record or return record, such as: String getNamebyid INT NID) // Returns the employee name according to the employee ID, only // read the name field here; (Tip: This is generally solved by performing a specific query or stored procedure) (4) For some aspects Considering (for example, the responsibility between each of the Layer in the N-Tier system), cannot (or prohibiting) the query filtering is performed through the database itself, and only the DataReader is filtered when reading! (Tip: Although DataView can achieve this purpose, its filtering premise is that all returned data must be read, so it is worse than DataReader!) U o / r mapping
O / R Mapping's full name is: Object Relational mapping, main purpose is to build a mapping relationship between traditional RDBMS and Oo Language, so that developers completely detach the data for a long-lasting sea.
About O / R mapping or recently comparing O / X mapping (You can refer to "programmer, 2004.01, p86"), may require a special article to discuss, this paper is mainly for the advantages and disadvantages of existing programs. Simple profiles and provide reference information in some practices.
Comparison of J2EE platforms, O / R mapping under .NET can be described as there is no history, and has not yet been tested programs. However, with the attention of major manufacturers, the pace of .Net O / R mapping has begun to keep up with the steps of this item to join the J2EE, and will not make more Many developers put .NET camp? J), which also makes numerous fatigates who come back and forth in SQL CLAUSE or ADO.NET to see "Light Road".
Next, let's take a look at the Solution of this slogan to discuss more than ADO.net.
Ø Open Source
Open source has always been with .NET keeps a certain distance, O / R mapping is even more than, but in terms of the author's download trial and source analysis, individuals think that the following two solutions still have a certain reference value: OPF, OJB.
Introduction to these two open source projects, you can refer to "Programmer, 2004.01, P13".
The full name of OPF is: Object Persistent Framework.
The full name of OJB is: Object Relational Bridge.
In implementation, the idea of these two programs is completely different, with respective representation.
The route of the OPF is a bit similar to Typed DataSet or Borland Eco (please refer to the following description), the implementation is relatively simple, providing more source level control; and the OJB implementation is similar to Microsoft Objectspaces (please refer to the following introduction), use The way the configuration file is complicated, relatively complicated. The basic framework of these two programs is as follows:
OPF:
It is not difficult to see from the figure:
(1) The Persistent class plays a DataSet role. In addition to the regular object data operations, the PersisTent operation can also set the relationship between different objects (such as the primary relationship, collection relationship, etc.) in the code generated by the Borland ECO. Slightly one or two), this is also the reason why the above say "provide more source level control";
(2) PersistentSqldataManager played the role of DataAdapter, performs real database operations by pre-set Commands; in actually written Employee Data Manager, developers do need to provide basic SQL statements, just like setting in SQLCommond (Borland ECO is further, replacing SQL with OCL);
(3) ObjectBroker's role is very important, it is the bridge between the objects and the data, the RegisterPersistent method establishes this virtual (Object) and reality (RDBMS) relationship;
(4) In the declaration of the Employee Business Object, the correspondence between the object attribute and the database field is reflected in the .NET Attribute mechanism, so modify it is still more convenient, although it is not flexible than the configuration file (please refer to OJB) Introduction), such as: need to recompile, developers have to pay attention to database fields.
OJB:
It is not difficult to see from the figure:
(1) The implementation of the scheme is more complicated, but the user needs to be actually written (only written EMPLOYEE Business Object), the key is to introduce the configuration file; at the same time, we are There is no need to call the RegisterObject method in similar OPF solutions (please refer to the OPF class diagram above), all of which (even database connection information), the system is as good!
(2) In this scenario, the SQL command is thoroughly replaced by the Criteria class, while QueryFacade acts as an Adapter functionality, communicating with the database through the true Command of PersistenceBroker;
(3) Whether it is a repository.xml configuration file, or the Criteria, QueryFacade class, we can find similar implementations in ObjectSpaces (please refer to the following introduction), at the same time, the author believes that this way It is also more in line with the spirit of O / R mapping, reducing the burden of developers! (4) OJB has a very cool tool "repositorygen.exe", can be used to generate the repository.xml configuration file (the same, source code is unpaid J), this, even ObjectSpaces can not do (want Think so many fields, attributes, associations, mapping, simply let people go crazy J)!
Microsoft Objectspaces This is a technology that makes many .NET Guy outstrettime a few years ago. As far as the author said, at that time, as long as I mentioned this topic, I usually returned to J2EE Guy's ridicule, I can't help myself, I'm also eNB (relative EJB) or NCMP (relative CMP). Finally, we can find it in the "Fang Rong" in the .NET Framework 1.2 (can be found in VS.NET 2004WHIDBEY or YUKON. First, let's see what the code written by ObjectSpaces looks like (still using the Employee example): // Initialize ObjectSpaceSqlConnection conn = new sqlConnection ("Data Source = localhost; integrated security = sspi; database = northwind"); Objectspace OS = New ObjectSpace ("Map.xml", Conn; // Returns its titleEEMPLOYEE OEMP = (EMPLOYEE) OS.GETOBJECT (Id = 1 ")); // Note = 1" : The actual field name is: employeeidstring start cut = Oemp.title; ... // Return all eligible EmployeeObjectSet = OS.GetObjectSet (NEPLOYEEE), ",", ","); // Note: Returning is not DataTable, but an object collection foreach (Employee OEMP IN OSET) {... // Note: You can do any operations on OEMP} For the second paragraph of the above, there is a solution, that is Inside the ObjectReader, the differences contained in the differences, similar to the DataSet / DataTable and DataReader between ADO.NET 1.0 (ADO.NET, which contains ObjectSpacesD, also known as ADO.NET 2.0) (have to admire Microsoft before and after Explanation in consistency, deepering the foreigner. J). Carefully analyze the above code, you can find it and the OJB discussed earlier has an amazing similar point (OJB Care only draws the basic types, but it can see this idea. Close up)! For example, the ObjectSpace class provides the QueryFacade feature in OJB; the ObjectQuery class provides a criteria feature in OJB; at the same time, both solutions do not have to use configuration files to store O / R mapping information. And the application generally performs data operation through these two classes. It is very convenient. Slightly different differences may be on the format of data (this, Objec TSPaces considers more details, refer to the code above), but this has not imposed on the actual code.
If you make a comparison of the code written under ObjectSpaces in ADO.NET, it is not difficult to see that the code given by ObjectSpaces is more readily read and understood, even if it is not familiar with the development of ADO.NET overall architecture. Personnel, you can easily pick up (only if the code involving RDBMS is only required to establish a database connection). For friends who have been familiar with ADO.NET or have been touched O / R mapping (such as hibernate under J2EE), it can be taken as a small dish! From the .NET Framework 1.2 document, you can know that ObjectSpaces provides a total of 3 namespaces, the overall structure is very clear: system.Data.Objectspaces.QuerySystem.Data.Objectspaces.SchemaObjectspaces, Query has been seen in the code Over, you can guess from your name, they are mainly responsible for providing basic access interfaces (such as query, increase / deletion / reform, etc.) and analyzes various query conditions (such as object filtering, etc.), and schema namespace is primarily used to operate O / r mapping profile and serve the class in other two namespaces. In ObjectSpaces, the O / R mapping profile mainly refers to Map.xml. The name of this file can be replaced at will, which is similar to the repository.xml in OJB. The other two configuration files describing the database structure and object structure are also very important: RSD.XML (Relational Schema Definition), OSD.XML (Object Schema Definition). You can understand the XSD files in Typed DataSet, without them, all data / object mapping and validation will be "illegal" J! In this article, the author is not prepared to explore ObjectSpaces, nor will it provide any Sample to explain its superiority. In this regard, .NET Framework SDK has long provided rich package.