vendredi 11 septembre 2015

Switching from Reflection to Expression API

Since reflection on a row by row basis is rather expensive, I've been looking for a faster alternative to build and insert entities. I did some research research on the subject and also found some performance comparisons which seem to indicate that the Expression API is the way to go. How would I rework the following function to take advantage of this?

    public static void InsertTable(IEnumerable<DataTable> chunkedTable)
    {
        Parallel.ForEach(
            chunkedTable,
            new ParallelOptions { MaxDegreeOfParallelism = Convert.ToInt32(ConfigurationManager.AppSettings["MaxThreads"]) },
            chunk =>
                {
                    Realty_Records_ProdEntities entities = null;
                    try
                    {
                        entities = new Realty_Records_ProdEntities();
                        entities.Configuration.AutoDetectChangesEnabled = false;

                        foreach (DataRow dr in chunk.Rows)
                        {
                            var parcelToInsert = new Parcel();

                            foreach (DataColumn c in dr.Table.Columns)
                            {
                                var propertyInfo = parcelToInsert.GetType()
                                    .GetProperty(
                                        c.ColumnName,
                                        BindingFlags.SetProperty | BindingFlags.IgnoreCase
                                        | BindingFlags.Public | BindingFlags.Instance);

                                if (propertyInfo == null)
                                {
                                    continue;
                                }

                                propertyInfo.SetValue(
                                    parcelToInsert,
                                    TaxDataFunction.ChangeType(
                                        dr[c.ColumnName],
                                        propertyInfo.PropertyType),
                                    null);
                            }
                            entities.Parcels.Add(parcelToInsert);
                        }
                        entities.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        TaxDataError.AddTaxApplicationLog(
                            TaxDataConstant.CategoryError,
                            ex.Source,
                            ex.Message,
                            ex.StackTrace);
                        throw;
                    }
                    finally
                    {
                        if (entities != null)
                        {
                            entities.Dispose();
                        }
                    }
                });
    }





Aucun commentaire:

Enregistrer un commentaire