17

I experimented with Dapper and Dapper.Contrib. I have the following class:

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public bool Active { get; set; }
}

It is beeing mapped to the table "Customers" which is pluralized. Is there a simple way to make Dapper use singular table names for all tables?

trenki
  • 7,133
  • 7
  • 49
  • 61
  • Possible duplicate of [Dapper sqlmapperextensions automatically adds "s" to tablename?](http://stackoverflow.com/questions/27341079/dapper-sqlmapperextensions-automatically-adds-s-to-tablename) – Chris Marisic Mar 21 '16 at 14:34

2 Answers2

24

Dapper.Contrib supports the Table attribute. Use it to manually specify the name of the table that an entity uses. See the docs for further information.

Alternatively there is a static delegate on SqlMapperExtensions called TableNameMapper. You can replace this with an implementation that performs the pluralization. PluralizationService in the framework can help you here.

It is used as follows:

SqlMapperExtensions.TableNameMapper = (type) => {
    // do something here to pluralize the name of the type
    return type.Name;
};
Dean Ward
  • 4,793
  • 1
  • 29
  • 36
  • I tried to implement a function using that delegate, but no luck. Could you please give more details with an example of how to use `SqlMapperExtensions`? Especially on `// do something here to pluralize the name of the type` part, assuming that we have POCO class Student, which is pluralized by Dapper and becomes Students. Also, I have created a question: [link](https://stackoverflow.com/questions/60600746/how-to-properly-singularize-table-names-with-dapper-contrib) – Elshad Shabanov Mar 09 '20 at 12:42
  • the docs link above is broken. Correct docs link for [specialized attributes](https://github.com/DapperLib/Dapper.Contrib#special-attributes) – PBMe_HikeIt Jul 01 '21 at 15:00
0

Use the 'Table' data annotation attribute on your entity class as follows:

[Table("Customer")]
public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public bool Active { get; set; }
}
leighhydes
  • 77
  • 1
  • 2
  • 8