Search code examples
c#sqlasp.net-mvcdapper-extensions

Dapper returns SQL conversion error on ID column


In my database I have an ID column that is a nvarchar type because it contains unique user names. In my .Net MVC application I am using Dapper to handle the database exchange. I then use the DapperExtensions.Get(dynamic id) on my models to grab a specific entry by the ID field. This works great in all cases except in users where I get the following error:

Conversion failed when converting the nvarchar value 'abcdefg' to data type int.'

I know that this is the ID column because that value exists in the ID property of my User model when it is used to extract the entity using Dapper. My best guess is that maybe Dapper expects that the dynamic id argument would be an int and tries to use it as such. I'm hoping to get some clarification on this by someone who understands it better than myself.

I have made sure that my database table uses nvarchar for this field and it is marked as the Primary Key.

Thanks


Solution

  • Make sure to use Dapper.Contrib.Extensions.Key attribute to flag the correct property as the Key property. Do not use System.ComponentModel.DataAnnotations.Key as it may act differently.

    However, sometimes, this is known to not work. When no Key attribute is present, try putting the field to the top of your class and DapperExtensions may treat this as your Primary Key.

    Or try using ExplicitKey?