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

1

6

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?

Idocrase answered 8/2, 2016 at 14:4 Comment(3)
Rewrote title to form a question (more readable in search-results) and some code-formattingAddress
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")].Daile
@Daile Thats how i solve it today when creating a generic repo. But as you said MatchNamesWithUnderscores works so well.Idocrase
N
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"));

    }
}
Numerator answered 9/2, 2016 at 23:47 Comment(2)
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.Idocrase
I'm not aware of such feature. By default, your "POCO property names should match each column name in the table," else, custom mapping.Numerator

© 2022 - 2024 — McMap. All rights reserved.