Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

dapper

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?

like image 927
Jim Geurts Avatar asked Feb 25 '12 00:02

Jim Geurts


1 Answers

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
like image 70
Marc Gravell Avatar answered Nov 15 '22 08:11

Marc Gravell