Mysoft. Data from entry to master series (4) [data insertion]

Source: Internet
Author: User
ArticleDirectory
    • Advanced usage of the item. Detach () method

The previous chapter explains how to configure dbsession. This chapter focuses on using mysoft. Data to insert data.

Here we will first reference the configuration of dbsession in the previous chapter.Code

 Dbsession Configuration      /// <Summary>      /// Database category      /// </Summary>      Public   Static   Class Dataaccess { /// <Summary>          /// Instantiate the dbsession through the configuration section         /// </Summary>          Public   Static   Readonly Dbsession defaultsession = New Dbsession (" Dataexample "); /// <Summary>          /// Instantiate dbsession through custom classes          /// </Summary>          Public   Static   Readonly Dataexample examplesession = New Dataexample ();}/// <Summary>      /// Dataexample session class      /// </Summary>      Public   Class Dataexample: dbsession { Public Dataexample (): Base (" Dataexample "){# If Debug This . Registersqllogger (log => {system. Io. file. writealltext (" C: \ log.txt ", Log) ;}); # endif}/// <Summary>          /// Insert an object          /// </Summary>          /// <Typeparam name = "T"> </typeparam>          /// <Param name = "item"> </param>          /// <Returns> </returns>          Public   Int Insert <t> (T item) where T: entity {item. Detach (); Return   Base . Save (item );} /// <Summary>          /// Update an object         /// </Summary>          /// <Typeparam name = "T"> </typeparam>          /// <Param name = "item"> </param>          /// <Returns> </returns>          Public   Int Update <t> (T item) where T: entity {item. Attach (); Return   Base . Save (item );}}

For the configuration of dbsession in the previous section, we can see that there are two methods for the dataexample class, but there is no insert <t> (T item) in my component) instead of the update <t> (T item) method, it is merged into a save <t> (T item) method. attach () and item. detach () to change the state of an object.

Note: The item. Attach () and item. Detach () methods have more powerful usage. We will focus on the following!

Some people may think that it is difficult to differentiate insertion and modification when merging them. It is better to distinguish them by method name directly. Of course, OK. Simply add two methods here, you can also expand more methods to meet your project development needs. For example, you can expand a method to save multiple objects as follows:

 Expansion of inserting multiple data entries at a time   //    // insert multiple data entries at a time   //    // 
     
       //     // 
     
      Public   int  insert 
   
     (ilist 
    
      items) where T: entity {
      int  ret = 0; 
      foreach  (T item 
      in  items) {RET + = insert (item );} 
      return  RET ;}
    
   

It is good to distinguish by method names. However, if you need to save an object list, some objects in this list need to be inserted, some need to be updated, and how do you deal with them, there is only one way to split the list into two parts for insertion and update.

However, using a save <t> (T item) method can easily solve this problem. The External Department calls the method to be inserted. detach (), the object to be updated calls item. attach (), and then input an internal operation. You can also set inserted or updated fields for each object! Is it more elegant to use, as shown below:

 
Simple Application of the detach () methodProducts Product =NewProducts () {productname ="Test product 1"}; Dataaccess. examplesession. Save (product); product. Detach (products. _. unitprice); dataaccess. examplesession. Save (product );
 
 

If some fields in the database have default values, for example, if the date field needs to be saved as getdate (), you can use the detach () method to remove the fields without inserting them!

Now let's talk about dbsession method extensions and simple applications. Next we will explain how to use dbsession to insert data. Let's take a look at how mysoft. Data brings you a powerful functional experience and quick development!

The following operations take the database northwind as an example.

 

I. Forced data insertion

 

Preparations:

Create a project named mysoftexample. dataentity. Use the tool to generate entities for all the tables in northwind. The generated results will also set the namespace to mysoftexample. dataentity.

After the preceding object project is generated, create a new mysoftexample. Web project and add the mysoftexample. dataentity project to the reference of the current project. The following describes how to operate the data through the generated object.

The following operations take the products object as an example:

1. Insert a single object data

Insert a single object// Instantiate a products objectProducts Product =NewProducts () {productname ="Test product 1"};// Insert a single objectDataaccess. examplesession. Save (product );

2. Batch object data insertion

Insert a group of Objects// Instantiate a group of products objectsList <Products> List =NewList <Products> ();For(IntIndex = 0; index <10; index ++) {list. Add (NewProducts () {productname ="Test Product"+ Index });}// Save data in batchesDbbatch batch = dataaccess. examplesession. beginbatch (10); list. foreach (item => {batch. Save (item) ;}); batch. Process ();

3. Insert a single entity with transactions (dbtrans built in mysoft. Data)

 
Insert a single object (built-in transaction)// Instantiate a products objectProducts Product =NewProducts () {productname ="Test product 1"};// Insert data using transactionsUsing(Dbtrans trans = dataaccess. examplesession. begintrans ()){Try{TRANS. Save (product); Trans. Commit ();}Catch{TRANS. rollback ();}}

4. Batch entity insertion with transactions (dbtrans built-in implementation of mysoft. Data)

 Insert a group of objects (built-in transactions)              // Instantiate a group of products objects List <Products> List = New List <Products> (); For ( Int Index = 0; index <10; index ++) {list. Add ( New Products () {productname =" Test Product "+ Index });} // Use transactions for batch data insertion              Using (Dbtrans trans = dataaccess. examplesession. begintrans ()){ Try {Dbbatch batch = trans. beginbatch (10); list. foreach (item => {batch. save (item) ;}); batch. process (); Trans. commit ();} Catch {TRANS. rollback ();}}

5. Create external database links for insertion

Insert a single object (external link)// Instantiate a products objectProducts Product =NewProducts () {productname ="Test product 1"};Using(System. Data. Common. dbconnection conn = dataaccess. examplesession. createconnection ()){// Insert a single objectDataaccess. examplesession. setconnection (conn). Save (product );}

Note: Batch inserts can be processed in the same way!

6. Create external database transactions and insert them

  insert a single object (external transaction)    // instantiate a products object  Products Product =  New  Products () {productname = " test product 1 " };< span style = "color: # 0000ff "> using  (system. data. common. dbtransaction trans = dataaccess. examplesession. begintransaction () { try  { // insert a single object  dataaccess. examplesession. settransaction (trans ). save (product); Trans. commit () ;}< span style = "color: # 0000ff"> catch  {TRANS. rollback () ;} 

Note: Batch inserts can be processed in the same way!

 

Advanced usage of the item. Detach () method

 

1. specify certain fields to use the default data value (do not change the status of the original object)

// Exclude certain fields during insertion
Detach (ParamsField [] removefields );

// The categoryid field is not inserted.
Product. Detach (products. _. categoryid );

// Excludefield fields included during insertion
// Call the Remove Method of field. All or products. _. All to exclude the inserted field and return the excludefield
// That is to say, detach will exclude all fields except remove.
Detach (excludefield field );

// Insert only the productname Field
Product. Detach (field. All. Remove (products. _. productname ));

 

Note:

If the transmission status of the original object is not changed, if the product object has been called outside, for example:

Previously, product. Detach (product. _. supplierid) was called );

If you call this operation again, the categoryid will be excluded from the original, which means that neither supplierid nor categoryid is inserted. The following detachall () method clears all previous statuses, then proceed with the current processing.

2. specify certain fields to use the default data value (change the status of the original object)

 
// Exclude certain fields during insertionDetachall (ParamsField [] removefields );// The categoryid field is not inserted.Product. detachall (products. _. categoryid );// Excludefield fields included during insertion// Call the Remove Method of field. All or products. _. All to exclude the inserted field and return the excludefield// That is to say, detachall will exclude all fields except remove.Detachall (excludefield field );// Insert only the productname FieldProduct. detachall (field. All. Remove (products. _. productname ));

Use of the insertorupdate Method

 

This method can be used when the user does not know whether the current entity exists in the database.

Internally, the system checks whether the object exists in the Database Based on the primary key, and then automatically calls the corresponding method for processing.

 
CodeProducts Product =NewProducts () {productid = 1, productname ="Test Product"}; Dataaccess. examplesession. insertorupdate (product );

Of course, there are other ways to insert data (you can study it slowly ):

CodeDataaccess. examplesession. Insert <Products> (NewField [] {products. _. productname },New Object[] {"Test Product"});IntProductid; dataaccess. examplesession. Insert <products,Int> (NewField [] {products. _. productname },New Object[] {"Test Product"},OutProductid );

 
 


2. insertcreator data insertion 

You can also use the insert creator to achieve the above results, or perform data insertion in a generic manner. Generally, the Creator is used to directly perform operations on tables and fields without creating object entities.

1. Insert an object through an object

 
CodeInsertcreator Ic = insertcreator. newcreator (). From <Products> (). setentity <Products> (product); dataaccess. examplesession. excute (IC );

2. Insert data using string tables and fields

CodeInsertcreator Ic = insertcreator. newcreator (). From ("Products"). Addinsert ("Productname","Test Product"); Dataaccess. examplesession. excute (IC );

3. insert data using string tables and fields and return the column Value

CodeInsertcreator Ic = insertcreator. newcreator (). From ("Products"). Addinsert ("Productname","Test Product"). Setidentityfield ("Productid");IntProductid; dataaccess. examplesession. excute (IC,OutProductid );

In the above method, you can also use transactions to operate Trans. excute (IC );

Here is a brief introduction. More functions can be realized only when used.

 

The data insertion Operation is explained here. The next chapter will explain the data modification (update) operation.

Any questions can be found here: mysoft component problem feedback and troubleshooting

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.