Fastest Way of Inserting in Entity Framework

前端 未结 30 2195
鱼传尺愫
鱼传尺愫 2020-11-21 05:23

I\'m looking for the fastest way of inserting into Entity Framework.

I\'m asking this because of the scenario where you have an active TransactionScope a

30条回答
  •  一生所求
    2020-11-21 05:52

    I agree with Adam Rackis. SqlBulkCopy is the fastest way of transferring bulk records from one data source to another. I used this to copy 20K records and it took less than 3 seconds. Have a look at the example below.

    public static void InsertIntoMembers(DataTable dataTable)
    {           
        using (var connection = new SqlConnection(@"data source=;persist security info=True;user id=;password=;initial catalog=;MultipleActiveResultSets=True;App=EntityFramework"))
        {
            SqlTransaction transaction = null;
            connection.Open();
            try
            {
                transaction = connection.BeginTransaction();
                using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
                {
                    sqlBulkCopy.DestinationTableName = "Members";
                    sqlBulkCopy.ColumnMappings.Add("Firstname", "Firstname");
                    sqlBulkCopy.ColumnMappings.Add("Lastname", "Lastname");
                    sqlBulkCopy.ColumnMappings.Add("DOB", "DOB");
                    sqlBulkCopy.ColumnMappings.Add("Gender", "Gender");
                    sqlBulkCopy.ColumnMappings.Add("Email", "Email");
    
                    sqlBulkCopy.ColumnMappings.Add("Address1", "Address1");
                    sqlBulkCopy.ColumnMappings.Add("Address2", "Address2");
                    sqlBulkCopy.ColumnMappings.Add("Address3", "Address3");
                    sqlBulkCopy.ColumnMappings.Add("Address4", "Address4");
                    sqlBulkCopy.ColumnMappings.Add("Postcode", "Postcode");
    
                    sqlBulkCopy.ColumnMappings.Add("MobileNumber", "MobileNumber");
                    sqlBulkCopy.ColumnMappings.Add("TelephoneNumber", "TelephoneNumber");
    
                    sqlBulkCopy.ColumnMappings.Add("Deleted", "Deleted");
    
                    sqlBulkCopy.WriteToServer(dataTable);
                }
                transaction.Commit();
            }
            catch (Exception)
            {
                transaction.Rollback();
            }
    
        }
    }
    

提交回复
热议问题