Automatically trim white space from columns when mapping with Dapper

ado.net c# dapper

Question

I'm using Dapper to hit a legacy database and there's whitespace padding on the column.

The solution I've found is to add properties like:

private string _status;
public string status 
{
    get { return _status; }
    set { _status = value.Trim(); }
}

Obviously this is tedious to do on every string member of every model that will interact with this database. According to the MSDN Entry on SET ANSI_PADDING, modifying this to OFF isn't an option either.

As the database is not mine, I'm unable to change it to nvarchar or simiar.

Is there an easy way to force Dapper to trim every string column that it reads from the database?

Popular Answer

One way is to write an extension method and use reflection to trim all string properties on the class. For example:

public static class ObjExt
{
    public static void Trim<T>(this T item)
    {
        var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var p in properties)
        {
            if (p.PropertyType != typeof(string) || !p.CanWrite || !p.CanRead) { continue; }
            var value = p.GetValue(item) as string;
            p.SetValue(item,value.Trim());
        }
    }
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why