Best practices for rapid development and design of LINQ (2) building a model

Source: Internet
Author: User
Tags connection reset
ArticleDirectory
    • 1. LINQ and LINQ to SQL
    • 2. model object of LINQ to SQL
    • 1. Modify the model class name
    • 2. Add default values and comments for all attributes.
    • 3. Add the isversion attribute to the column attribute of the primary key column. The value is true.
    • 3. Add column (isdbgenerated = true) to the default model attribute of the database)
    • 4. Modify the datacontext class
    • 5. Add the xmlignore feature label for reverse reference
    • 1. If there are propertychanged and propertychanging members, set it to null.
    • 2. Set all entityset and entityref fields of the model class to the default value.
I. Summary

In the first article, I briefly introduced the design framework of the Project and the idea of implementing LINQ. This article will be the most practical and skillful part, that is, how to create a model object of the LINQ to SQL statement.

Ii. Preface 1. LINQ and LINQ to SQL

Jiang min reminded me to pay attention to the differences between LINQ to SQL and LINQ. indeed, the two are similar to C # And. net. lao Zhao wrote an article with special emphasis on the differences between the two. here is a brief introduction.

LINQ is short for language-Integrated Query. After translation, it is "integrated language query". I think of LINQ as a query framework with its own specific syntax. as long as the object implements the interfaces required by the LINQ framework, you can use the LINQ syntax for query. for example:

VaR query = from tagcategoryInDC. tagcategoryWhereTagcategory. pkid = tagcategoryid select tagcategory

 

LINQ to SQL is a LINQ provider that can implement lightweight Orm. The role of ORM is to map tables and model models in the database, such as hiberate (.. net ). with the help of LINQ to SQL, we can operate the model object in the LINQ language to perform crud operations on the database.

Why can we query an object in the LINQ language? This is because of the following.

Why can we query objects to operate databases using the LINQ language? Because we have LINQ to SQL.

2. model object of LINQ to SQL

The traditional model object is an information model. The model class generally does not contain any methods, but only attributes. to describe a real-world student, you first need a model class of Student. For example, the class name is called student, which is used to save the unique information of each student, such as the name. then, describe the behavior in the business logic layer. For example, create a studentbl class in the business logic layer and add a walk () method to it. currently, it is quite popular to use business models to design systems. Business Models abstract information and behavior into a student role. but I rarely use it.

Using LINQ to SQL, we can map a property of the model in the traditional sense, such as the name attribute of the student class to the name field of the student table in the database. This is Orm: description of relational ing of Object Relationships. with Orm, when we modify the name of student, the data in the database will be automatically modified. we can no longer see SQL, and the system is all operating objects.

The visual design tool "O/R designer" and the command line tool sqlmetal.exe provide a model class automatically generated for tables in the database.Code. However, the Code generated by default can only be used as a simple demo. There are many problems and problems to be modified in the actual application. next we will share with you the "best practices" for creating a model object.

3. Use tools to create model classes

In architecture, I cut the model class horizontally into one layer, and vertically cut each business into a project. For example, the model layer of the tag system is com. elong. model. Tag.

Each project must first create a model class for each table. In this step, I will use the visual design of the O/R designer. The following describes the procedure.

1. Use the O/R designer

To add a new item to the project, select "LINQ to SQL class", for example:

We will add the tagdatacontext. dbml file to the project, expand the "+" file, and find that it contains two sub-Files: tagdatacontext. dbml. layout and tagdatacontext. Design. CS

In the example, tagdatacontext. Design. CS stores the datacontext class and the model class code of all tables. tagdatacontext. dbml. layout stores some information about the visual design.

Double-click tagdatacontext. dbml files enter the visual design stage. it is very simple to use the O/R designer. if you want to learn, you can refer to msdn or a series of tutorials provided by some predecessors. This is nothing more than a drag-and-drop job. the following is an O/R designer:

Provide the following skills and experience:

1.If you want to automatically create the relationship between the two tables in the database, you need to drag the two tables out at the same time.

2.Click the blank area of the designer to view the attribute panel. You can modify many attributes here:

The most useful context and object namespaces. the context namespace is the namespace of the datacontext class. I usually place it in the dataaccess layer. the object namespace is the namespace where all model classes are located. I place it in the model layer.

3.Any modifications made to the visual design will overwrite the. Design. CS file, so do not modify the file manually at this stage, because once modified, the O/R designer cannot be used.

4.The o/R designer allows us to create a class that will not be overwritten to expand it into automatically generated code. The creation method is to right click in the blank space of the O/R designer, in the pop-up menu, select "view code ",:

A. CS file will be added to the. dbml file:

Please be sure to create this file, because I will create the model class method in this file later.

Iv. Use sqlmetal.exe

Sqlmetal.exe is a command line tool that needs to be used from the command line of Visual Studio. It also generates code for the datacontext and model classes. For example:

Sqlmetal/Conn:"Uid = *****; Pwd = *****; initial catalog = databasename; Data Source = 192.168.0.1; Connect timeout = 900; Connection Reset = false"/Code:"D: \ dB. cs"

DB. CS contains the datacontext of all tables in the database and the model class of each table.

Once the visualization design is generated. design. the CS file has been modified. For example, if you have added comments, do not use the O/R designer for visual changes. the correct method is manual modification. design. the code in CS, for new table addition and other heavy workload changes, you can first use sqlmetal.exe to generate the initial code of the model class corresponding to the table, copy it. design. CS, and then modify it.

5. Modify the tagdatacontext. Design. CS File

In design. CS, we need to modify the following items:

1. Modify the model class name

Modify the model class name and the value of the model class Table feature, and remove the "user." prefix. Add comments. The following is an example.

Before modification:

 
[Table (name ="DBO. t_activity")]Public Partial ClassT_activity

After modification:

 
/// <Summary>/// Activity table. Save various activity information/// </Summary>[Table (name ="T_activity")]Public Partial ClassActivity

 

2. Add default values and comments for all attributes.

Take the activityname attribute as an example.

Add default value:

 
Private String_ Activityname =String. Empty;

Add notes:

  //    // activity name   //   [column (storage =  "_ activityname" , dbtype =  "nvarchar (200) not null" , canbenull =  false )]  Public   string  activityname 

 

3. Add the isversion attribute to the column attribute of the primary key column. The value is true.

For example:

  //    // auto-incrementing primary key   ///   [column (storage =  "_ pkid" , autosync = autosync. oninsert, dbtype =  "int not null identity" , isprimarykey =  true , isdbgenerated =  true , isversion =  true )]  Public   int  pkid 

This article is very important. Otherwise, you will encounter many problems when using LINQ. Of course, you can also create an additional timestamp column to use it as an isversion column, but it is troublesome.

For primary keys, the autosync attribute should be set to oninsert. The function is that when we want to insert an object, the primary key ID of no object before insertion is null or default, however, after datacontext is called to complete the insert operation, the primary key ID attribute of this object will be automatically filled.

3. Add column (isdbgenerated = true) to the default model attribute of the database)

For example:

[Column (storage ="_ Createdtime", Dbtype ="Datetime not null", Isdbgenerated =True)]PublicSystem. datetime createdtime {...}

Createdtime is written when getdate () is used in the database during creation. We want to use the value in the database insteadProgramUpdate in. Note that objects are updated using LINQ. If the default code is used and isdbgenerated is not added, the getdate () in the database will be invalid.

4. Modify the datacontext class

If a new table is added. design. the model class in CS also needs to modify the datacontext class in this file. to add an activity table, add the following code to the datacontext class:

 
Partial VoidInsertactivity (activity instance );Partial VoidUpdateactivity (activity instance );Partial VoidDeleteactivity (activity instance );PublicSystem. Data. LINQ. Table <activity> activity {get {Return This. Gettable <activity> ();}}

These three distribution methods are the mechanisms provided by LINQ, which can be used to customize addition, deletion, modification, and modification operations. The activity attribute is the database table object that needs to be used in the LINQ statement.

5. Add the xmlignore feature label for reverse reference

The top and bottom directions refer to "1" in one-to-many mode as the top, and the leaf node is a metadata table or "many-to-many" table.

In actual code, the [xmlignore ()] feature is added to the attributes corresponding to all entityref <t> fields. Otherwise, when the remote service needs to serialize the object, A circular reference is displayed.

6. Modify the tagdatacontext. CS File

In the. CS file created through the O/R designer above, add a detach method for each class. Below is a standard detach method:

[Datacontract ()] Public   Partial   Class Tagcategory { Public   Void Detach (){ This . Propertychanged = Null ; This . Propertychanging = Null ; This . _ Tagcategorylanguage = New Entityset <tagcategorylanguage> ( New Action <tagcategorylanguage> ( This . Attach_tagcategorylanguage ), New Action <tagcategorylanguage> ( This . Detach_tagcategorylanguage )); This . _ Tagcategoryrefcity = New Entityset <tagcategoryrefcity> ( New Action <tagcategoryrefcity> ( This . Attach_tagcategoryrefcity ), New Action <tagcategoryrefcity> ( This . Detach_tagcategoryrefcity )); This . _ Tagitem = New Entityset <tagitem> ( New Action <tagitem> ( This . Attach_tagitem ), New Action <tagitem> ( This . Detach_tagitem )); This . _ Tagcategory1 = New Entityset <tagcategory> ( New Action <tagcategory> ( This . Attach_tagcategory1 ), New Action <tagcategory> ( This . Detach_tagcategory1 )); This . _ T_tag_tagcategory1 =Default (Entityref <tagcategory> );}}

A partial class can distribute class code in multiple files, so we can expand the model class in the. CS file.

A standard detach method requires the following:

1. If there are propertychanged and propertychanging members, set it to null.

As long as the model class implements the inotifypropertychanging and inotifypropertychanged interfaces, there will be two event delegation: propertychanged and propertychanging. The default model class implements these two interfaces.

2. Set all entityset and entityref fields of the model class to the default value.

This part of the code can be found in the automatically generated model class constructor. You need to copy it to this method.

In my LINQ framework, each model class must have a detach method.

VII. Roles of Detach

The main function of Detach is to remove an object from the datacontext trace and implement a method: update. The parameter is the model object model.

After detach an object, we can call our own business logic or data access layer object to update the object, instead of relying on datacontext every time.

If you rely on datacontext, you cannot split your business logic and responsibilities. if you already have an object with complete information, you will often encounter attach failures when you do not call the detach method. select is required for each update, which is obviously heavy and affects efficiency.

Some people may still have the correctness of this method so far. because I don't know the underlying Object Tracking Mechanism of LINQ, I don't know why. however, I spent a few days searching for this detach method. Because there is no relevant information in Chinese, the English document also tested several solutions before verifying the feasibility of this method in the event.

With detach, the update method of the data access layer can be written as follows:

         # Region ===== Update ==== /// <Summary>          /// Update object          /// </Summary>          /// <Param name = "item"> tagcategory object </param>          /// <Returns> change set </returns>          Public Changeset Update (tagcategory item) {tagdatacontext Dc = New Tagdatacontext (m_connectionstring); item. Detach (); DC. tagcategory. Attach (item, True ); Changeset result = Dc. getchangeset (); DC. submitchanges (); Return Result ;} /// <Summary>          /// Update the Set          /// </Summary>          /// <Param name = "item"> tagcategory set </param>          /// <Returns> change set </returns>          Public Changeset Update (list <tagcategory> itemlist) {tagdatacontext Dc =New Tagdatacontext (m_connectionstring ); Foreach (Tagcategory tempitem In Itemlist) {tempitem. Detach ();} DC. tagcategory. attachall (itemlist, True ); Changeset result = Dc. getchangeset (); DC. submitchanges (); Return Result ;} # Endregion 

 

8. Summary

Some may want to criticize the efficiency of my LINQ architecture. first of all, we can be sure that my update method will produce the correct operation. For example, we can certainly update an object to the database. using the follow-up and update mechanism of LINQ to SQL does not improve the efficiency much. Instead, it often encounters problems, and there is no way to split duties.

At least I have provided a solution, and I have not found the Framework Design for the second kind of LINQ.

after the model layer is finished, the business logic layer and data access layer objects are explained. the rest of the work is easy. I only need to provide complete code and explain some key points. the model class is definitely the key point of LINQ to SQL. I think this article is better than the previous one, because I spent my time organizing and making statements. welcome to continue building bricks!

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.