How can I make Dapper.NET throw when result set has unmapped columns?

dapper

Question

Using the example code below as context... When I run this query I get the 'Id' field coming back as default value (which is 0 for an int). I would like to tell dapper to run in a manner where it would throw an exception if there is a column in the result set that does not get mapped to a property on my result object. (I understand that the issue is just that I need to remove the extra 'd' in the SQL query but I'm interested in having this expose itself more explicitly)

I've been unable to find anything on this topic. Please let me know if this is even possible with Dapper.

Thanks in advance (besides this issue, and for anyone who hasn't taken the plunge, Dapper really is the greatest thing since sliced bread!).

class CustomerRecord
{
    public int Id { get; set; }
    public string Name { get; set; }
}

CustomerRecord[] GetCustomerRecords()
{
    CustomerRecord[] ret;
    var sql = @"SELECT 
                 CustomerRecordId AS Idd, 
                 CustomerName as Name
                 FROM CustomerRecord";

    using (var connection = new SqlConnection(this.connectionString))
    {
        ret = connection.Query<CustomerRecord>(sql).ToArray();
    }

    return ret;
}

Popular Answer

You could create your own type map where you use Dapper's DefaultTypeMap and throw an exception when it cannot find the member:

public class ThrowWhenNullTypeMap<T> : SqlMapper.ITypeMap
{
    private readonly SqlMapper.ITypeMap _defaultTypeMap = new DefaultTypeMap(typeof(T));

    public ConstructorInfo FindConstructor(string[] names, Type[] types)
    {
        return _defaultTypeMap.FindConstructor(names, types);
    }

    public ConstructorInfo FindExplicitConstructor()
    {
        return _defaultTypeMap.FindExplicitConstructor();
    }

    public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
    {
        return _defaultTypeMap.GetConstructorParameter(constructor, columnName);
    }

    public SqlMapper.IMemberMap GetMember(string columnName)
    {
        var member = _defaultTypeMap.GetMember(columnName);
        if (member == null)
        {
            throw new Exception();
        }
        return member;
    }
}

Downside of this, is that you have to configure all the type maps for every entity:

SqlMapper.SetTypeMap(typeof(CustomerRecord), typeof(ThrowWhenNullTypeMap<CustomerRecord>));

This could be configured using reflection, however.



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