4

I am trying out Dapper. I like what I have seen so far. In order to do simple CRUD, I use Dapper.rainbow. It works very well. However, it works only if the table has identity column with name Id. It makes sense to have db like that but I can not ask for column name change in database just to use Dapper. To be more clear, I am working with database like Northwind Db. It has tablename repeated in Id column everywhere.

In order to handle this,I changed the Dapper.Rainbow code as below:

   public T Get(TId id,string idColumnName="Id")
        {
            return database.Query<T>("select * from " + TableName + " where               "+idColumnName+" = @id", new { id }).FirstOrDefault();
        }

Is there a better way to handle this such as Column mapping /annotations or something completely different?

I have read questions like these

Manually Map column names with class properties

Dapper.Rainbow VS Dapper.Contrib

( I came across similar little problem with Dapper.Contrib, I will ask it separately).

Update - Not sure if the answers are applicable to my Dapper.Rainbow problem here (Atleast, I don't see how).

Thanks for help in advance!

Community
  • 1
  • 1
Yogiraj
  • 1,952
  • 17
  • 29

1 Answers1

7

I had a similar problem. The existing Dapper extensions did not fit my ideal pattern. I wanted simple CRUD operations with smart defaults without anything extra. I also wanted to have models with additional properties that did not directly map to the database. For example - a FullName property that combines FirstName and LastName in its getter - and not add FullName to the Insert and Update statements.

I wanted the primary key column to be Id in most cases but allow overriding with an attribute.

Finally, I wanted the table name to match the class name by default but allow overriding with an attribute.

I ended up writing my own extension to Dapper that solves these issues. Its on Github and Nuget. Hopefully it will be helpful to you.

https://github.com/ericdc1/Dapper.SimpleCRUD

ericdc
  • 11,217
  • 4
  • 26
  • 34
  • Is there nuget package for this? – Yogiraj Mar 15 '13 at 17:33
  • The T4 has a package too. https://nuget.org/packages/Dapper.SimpleCRUD.ModelGenerator/ – ericdc Mar 15 '13 at 23:26
  • +1 Fantastic! It works! I started writing a sample DAL layer based on Rainbow (https://github.com/YogirajA/Dapper.DAL) and bumped on to this issue. I was also using t4 template to generate pocos from DB but your template is much better. Now, I will use SimpleCrud for my DAL application and projects. Thanks very much! – Yogiraj Mar 16 '13 at 19:13
  • @ericdc Awesome work! You wouldn't have by chance a T4 generator for MySQL, would you? – AngryHacker Dec 20 '15 at 01:19
  • @ericdc, is it possible for you to add option to allow insert without the second sql statement which return the @@identity? This is to support MS Access/Jet. Thank you. – hubert17 Dec 20 '20 at 15:58