Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I specify DB column names for dapper-dot-net mappings?

Is there a way with dapper-dot-net to use an attribute to specify column names that should be used and not the property name?

public class Code
{
    public int Id { get; set; }
    public string Type { get; set; }
    // This is called code in the table.
    public string Value { get; set; }
    public string Description { get; set; }
}

I'd like to be able to name my properties whatever I choose. Our database has no consistent naming convention.

If not with dapper, are there any additional similar options?

like image 636
Walter Fresh Avatar asked Aug 29 '12 17:08

Walter Fresh


3 Answers

You can also check out Dapper-Extensions.

Dapper Extensions is a small library that complements Dapper by adding basic CRUD operations (Get, Insert, Update, Delete) for your POCOs.

It has an auto class mapper, where you can specify your custom field mappings. For example:

public class CodeCustomMapper : ClassMapper<Code>
{
    public CodeCustomMapper()
    {
        base.Table("Codes");
        Map(f => f.Id).Key(KeyType.Identity);
        Map(f => f.Type).Column("Type");
        Map(f => f.Value).Column("Code");
        Map(f => f.Description).Column("Foo");
    }
}

Then you just do:

using (SqlConnection cn = new SqlConnection(_connectionString))
{
    cn.Open();
    var code= new Code{ Type = "Foo", Value = "Bar" };
    int id = cn.Insert(code);
    cn.Close();
}

Keep in mind that you must keep your custom maps in the same assembly as your POCO classes. The library uses reflection to find custom maps and it only scans one assembly.

Update:

You can now use SetMappingAssemblies to register a list of assemblies to scan:

DapperExtensions.SetMappingAssemblies(new[] { typeof(MyCustomClassMapper).Assembly });
like image 99
Void Ray Avatar answered Oct 18 '22 21:10

Void Ray


If you are using a select statement directly or in a procedure you can just alias the columns.

SELECT code as Value FROM yourTable
like image 21
Rick Avatar answered Oct 18 '22 21:10

Rick


Another approach is to just manually map it with the dynamic result.

var codes = conn.Query<dynamic>(...sql and params here...)
                 .Select<dynamic,Code>(s=>new Code{Id = s.Id, Type = s.Type, Value = s.code, Description = s.Description});

Clearly this introduces type-safety scenarios because you are querying on dynamic. Also, you have to manually map columns which is a bummer.

However, I tend to like this approach because it's so darned transparent. You can cast if need be (as is the case with Enums), and basically just do whatever it is you need to do to go from the db recordset to your properties.

like image 4
BlackjacketMack Avatar answered Oct 18 '22 21:10

BlackjacketMack