samedi 22 septembre 2018

Optimize code for reduce Reflection impact on performance

I'm building a web API Rest on .Net Core and ADO.Net

I use this code to populate my model object from DataRow:

public IEnumerable<TEntity> Map(DataTable table)
    {
        List<TEntity> entities = new List<TEntity>();
        var columnNames = table.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();
        var properties = (typeof(TEntity)).GetProperties().ToList();

        foreach (DataRow row in table.Rows)
        {
            TEntity entity = new TEntity();
            foreach (var prop in properties)
            {
                PropertyMapHelper.Map(typeof(TEntity), row, prop, entity);
            }
            entities.Add(entity);
        }

        return entities;
    }

And use this other code for create the necesary SQL Update command:

protected void base_UpdateCommand(IDbCommand myCommand, TEntity entity, string sWhere)
    {
        var properties = (typeof(TEntity)).GetProperties().ToList();
        string sProps = "";
        string sCommand = "";

        foreach (var prop in properties)
        {                
            bool bIgnore = prop.GetCustomAttributes(true).Any(a => a is KeyAttribute);
            if (prop.Name.ToUpper() != sKeyField.ToUpper() && !bIgnore)
            {
                sProps = sProps + prop.Name + "=@" + prop.Name + ", ";

                var p = myCommand.CreateParameter();
                p.ParameterName = prop.Name;
                if (prop.GetValue(entity) == null)
                    p.Value = DBNull.Value;
                else
                    p.Value = prop.GetValue(entity);

                myCommand.Parameters.Add(p);
            }
        }
        sProps = sProps.Substring(0, sProps.Length - 2);

        sCommand = "UPDATE [" + sTable + "] SET " + sProps;
        sCommand = sCommand + " WHERE " + sWhere;

        myCommand.CommandText = sCommand;
    }

I know that reflection has impact on performance, so i'm looking for suggestion on how to improve this code. Thanks!





Aucun commentaire:

Enregistrer un commentaire