5

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?

  • 1
    Rewrote title to form a question (more readable in search-results) and some code-formatting – Frederik Struck-Schøning Feb 08 '16 at 14:57
  • 1
    That is too bad that the extension doesn't handle the mapping like in the parent namespace, because `DefaultTypeMap.MatchNamesWithUnderscores = true;` works so well. This puts a kink in the generic repository I'm building for a project. I believe the table name mapping works fine still if you decorate the class with `[Table("this_is_a_table")]`. – secretwep Mar 05 '16 at 00:38
  • @secretwep Thats how i solve it today when creating a generic repo. But as you said MatchNamesWithUnderscores works so well. –  Mar 05 '16 at 07:43

1 Answers1

3

It's pretty straightforward, 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"));

    }
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Void Ray
  • 9,849
  • 4
  • 33
  • 53
  • Sorry for not mention it in main post, but i want to be able to solve this mapping automatic for all entities. And only use the class mapper in special cases. Updated my post. –  Feb 10 '16 at 18:45
  • I'm not aware of such feature. By default, your "POCO property names should match each column name in the table," else, custom mapping. – Void Ray Feb 10 '16 at 21:33