How to map an identity column, that has a different name, with Dapper?

c# dapper

Question

I have a database with id columns like BookId, AuthorId, etc. My code files, however, just have an Id property. I'm attempting to convert parts of the program that use NHibernate with Dapper, so I'm trying to eliminate the need for both an Id and a BookId property on . NHibernate has a built in identity map that maps BookId to the Id property of Book objects and similarly AuthorId to the Id property on Author objects.

Is there a way to do this Dapper, outside of giving an alias to the column, in the sql query?

public class Book {
  public int Id { get; set; }
  public string Name { get; set; }
}

public class Author {
  public int Id { get; set; }
  public string Name { get; set; }
}

A sample query that I'm using looks like:

select * from Books b inner join Author a on a.AuthorId = b.AuthorId

If Dapper doesn't support this easily, any thoughts on what other options I have?

Accepted Answer

By design, dapper does not have a mapping layer. One step down that road, and before we know what has happened all of a sudden we'll be drowning in configuration files. So: two options:

  • add an alias in the SQL
  • add a shim in the C#

so either (sql):

select BookId as [Id], Name from Books

or (C#):

private int BookId { get { return Id; } set { Id = value; } } // just for dapper



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why