Stefan Karlsson February 2016

How do I bind underscore table/column names automatically using Dapper-Extensions?

I am naming my MYSQL tables and columns using underscore characters:

this_is_a_table should map to: ThisIsATable

this_is_a_column should map to: ThisIsAColumn

Dapper can handle this mapping if i set:

DefaultTypeMap.MatchNamesWithUnderscores = true;

Is there any way to enable this in Dapper-Extensions so that it maps undescore automatically?

Answers


Void Ray February 2016

It's pretty strait forward, you just need to create a custom mapping. Here is an example:

Create table:

create table hello_world
(
    Id int not null,
    Value_Column varchar(max)
)

Test:

public class World
{
    public int Id { get; set; }
    public string Value { get; set; }
}

public class WorldCustomMapper : ClassMapper<World>
{
    public WorldCustomMapper()
    {
        base.Table("hello_world");
        Map(f => f.Id).Column("Id");
        Map(f => f.Value).Column("Value_Column");
    }
}

[TestFixture]
public class Class1
{
    [Test]
    public void TestMappping()
    {
        var conn = new SqlConnection(@"Data Source=.\sqlexpress; Integrated Security=true; Initial Catalog=mydb");
        conn.Open();

        var record = new World
        {
            Id = 1,
            Value = "Hi"
        };

        conn.Insert(record);

        var result = conn.Get<World>(1);

        Assert.That(result.Value, Is.EqualTo("Hi"));

    }
}

Post Status

Asked in February 2016
Viewed 3,657 times
Voted 13
Answered 1 times

Search




Leave an answer