In the case of LINQ-to-SQL ~ Use reflection to implement the CU of Ado.net in the linq-to-SQL Environment

Source: Internet
Author: User
Returning to the directory for the CURD operation provided by linqtosql gives us the feeling that it is simple, easy to use, more object-oriented, and does not need to spell SQL statements, all of these benefits indicate that when processing a single entity or a small set length, if there is a 1000 collection entity, you want to perform the update operation. If you still use linqtosql to raise the updat

Returning to the directory for the CURD operations provided by linq to SQL gives us the feeling that they are simple, easy to use, more object-oriented, and do not need to spell SQL statements, all of these benefits indicate that when processing a single entity or a set with a small length, if there is a set entity of 1000, you want to perform the update operation, if you still use the updat file that is initiated by using linq to SQL

Back to directory

For the CURD provided by linq to SQLOperationIt makes us feel simple, easy to use, more object-oriented, and no need to spell SQL statements. These advantages indicate that when processing a single object or a small set of length, if there is a collection entity of 1000 entries, you want to updateOperationIf you still use the update method provided by linq to SQL, your server will be suspended soon.

Why?

For commands borrowed by LINQ, such as update (list ),It traverses the list in the foreache and sends an instruction to SQLSERVER.Good guy, if this is a set of 1000 million or million entities, update them.OperationThis is unacceptable for IO overhead and server performance. It should be an SQL link and a command to solve the problem!

Set your own CURD set with better performanceOperation(Self-selected entity framework architecture, not available for linq to SQL andImplementation)

////// SQLOperationType ///Protected enum SQLType {Insert, Update, Delete ,}////// Construct the Update statement string //////
 //////
 Private Tuple
 
  
CreateUpdateSQL
  
   
(TEntity entity) where TEntity: class {if (entity = null) throw new ArgumentException ("The database entity can not be null."); List
   
    
PkList = GetPrimaryKey
    
     
(). Select (I => I. name ). toList (); Type entityType = entity. getType (); var table = entityType. getProperties (). where (I =>! PkList. Contains (I. Name) & I. GetValue (entity, null )! = Null & I. PropertyType! = Typeof (EntityState )&&! (I. GetCustomAttributes (false). Length> 0 & I. GetCustomAttributes (false). Where (j => j. GetType () = typeof (NavigationAttribute ))! = Null) & (I. propertyType. isValueType | I. propertyType = typeof (string) // filter navigation attributes ). toArray (); // filter if (pkList = null | pkList. count = 0) throw new ArgumentException ("The Table entity have not a primary key. "); List
     Arguments = new List(); StringBuilder builder = new StringBuilder (); foreach (var change in table) {if (pkList. Contains (change. Name) continue; if (arguments. Count! = 0) builder. append (","); builder. append (change. name + "= {" + arguments. count + "}"); if (change. propertyType = typeof (string) | change. propertyType = typeof (DateTime) arguments. add ("'" + change. getValue (entity, null ). toString (). replace ("'", "char (39)") + "'"); else arguments. add (change. getValue (entity, null);} if (builder. length = 0) throw new Exception ("No attribute is updated"); builder. insert (0, "UPDATE" + string. format ("[{0}]", entityType. name) + "SET"); builder. append ("WHERE"); bool firstPrimaryKey = true; foreach (var primaryField in pkList) {if (firstPrimaryKey) firstPrimaryKey = false; else builder. append ("AND"); object val = entityType. getProperty (primaryField ). getValue (entity, null); builder. append (get1_statment (primaryField, arguments. count); arguments. add (val);} return new Tuple
       
         (Builder. ToString (), arguments. ToArray ());}///
        /// Create a Delete statement string //////
        ///
        ///
        Private Tuple
        
          CreateDeleteSQL
         
           (TEntity entity) where TEntity: class {if (entity = null) throw new ArgumentException ("The database entity can not be null. "); Type entityType = entity. getType (); List
          
            PkList = GetPrimaryKey
           
             (). Select (I => I. name ). toList (); if (pkList = null | pkList. count = 0) throw new ArgumentException ("The Table entity have not a primary key. "); List
            Arguments = new List(); StringBuilder builder = new StringBuilder (); builder. append ("Delete from" + string. format ("[{0}]", entityType. name); builder. append ("WHERE"); bool firstPrimaryKey = true; foreach (var primaryField in pkList) {if (firstPrimaryKey) firstPrimaryKey = false; else builder. append ("AND"); object val = entityType. getProperty (primaryField ). getValue (entity, null); builder. append (get1_statment (primaryField, arguments. count); arguments. add (val);} return new Tuple
              
                (Builder. ToString (), arguments. ToArray ());}///
               /// Construct the Insert statement string // when the primary key is auto-incrementing, if the primary key value is 0, we Insert the primary key into the SQL string //////
               ///
               ///
               Private Tuple
               
                 CreateInsertSQL
                
                  (TEntity entity) where TEntity: class {if (entity = null) throw new ArgumentException ("The database entity can not be null. "); Type entityType = entity. getType (); var table = entityType. getProperties (). where (I => I. propertyType! = Typeof (EntityKey) & I. PropertyType! = Typeof (EntityState) & I. Name! = "IsValid" & I. GetValue (entity, null )! = Null &&! (I. GetCustomAttributes (false). Length> 0 & I. GetCustomAttributes (false). Where (j => j. GetType () = typeof (NavigationAttribute ))! = Null) & (I. propertyType. isValueType | I. propertyType = typeof (string ))). toArray (); // filter the List of primary keys, navigation attributes, and status attributes.
                 
                   PkList = GetPrimaryKey
                  
                    (). Select (I => I. Name). ToList (); List
                   Arguments = new List(); StringBuilder fieldbuilder = new StringBuilder (); StringBuilder valuebuilder = new StringBuilder (); fieldbuilder. append ("insert into" + string. format ("[{0}]", entityType. name) + "("); foreach (var member in table) {if (pkList. contains (member. name) & Convert. toString (member. getValue (entity, null) = "0") continue; object value = member. getValue (entity, null); if (value! = Null) {if (arguments. Count! = 0) {fieldbuilder. append (","); valuebuilder. append (",");} fieldbuilder. append (member. name); if (member. propertyType = typeof (string) | member. propertyType = typeof (DateTime) valuebuilder. append ("'{" + arguments. count + "} '"); else valuebuilder. append ("{" + arguments. count + "}"); if (value. getType () = typeof (string) value = value. toString (). replace ("'", "char (39)"); arguments. add (value) ;}} fieldbuilder. append (") Values ("); fieldbuilder. append (valuebuilder. toString (); fieldbuilder. append (");"); return new Tuple
                     
                       (Fieldbuilder. ToString (), arguments. ToArray ());}///
                      /// Execute the SQL statement according to the SQLOperation//////
                      ///
                      ///
                      ///
                      Protected string DoSQL
                      
                        (IEnumerable
                       
                         List, SQLType sqlType) where TEntity: class {StringBuilder sqlstr = new StringBuilder (); switch (sqlType) {case SQLType. insert: list. toList (). forEach (I => {Tuple
                        
                          SQL = CreateInsertSQL (I); sqlstr. appendFormat (SQL. item1, SQL. item2) ;}); break; case SQLType. update: list. toList (). forEach (I => {Tuple
                         
                           SQL = CreateUpdateSQL (I); sqlstr. appendFormat (SQL. item1, SQL. item2) ;}); break; case SQLType. delete: list. toList (). forEach (I => {Tuple
                          
                            SQL = CreateDeleteSQL (I); sqlstr. appendFormat (SQL. item1, SQL. item2) ;}); break; default: throw new ArgumentException ("enter the correct parameter");} return sqlstr. toString ();}
                           

The road ahead is always the road to success, as long as you believe, it will be fasterImplementation...

Back to directory

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.