0

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!

ericpap
  • 2,917
  • 5
  • 33
  • 52

1 Answers1

0

You might consider using Dapper. It is a wrapper around ADO.NET so technically it can't be faster than ADO.NET, but in most cases it uses better coding practices comparing to custom code you use to manupulate data via ADO.NET, so potentially it could give the better performance results.

Dmitry Pavlov
  • 30,789
  • 8
  • 97
  • 121