Dapper Extensions - Object of type 'System.Int32' cannot be converted to type 'System.Int16'

dapper dapper-extensions

Question

I am using dapper extensions (SqlMapperExtensions.cs).

When doing a simple insert:

db.Insert<Student>(student);

I get an exception:

Object of type 'System.Int32' cannot be converted to type 'System.Int16'.

The Id type in the db is SmallInt.
The Id type in the POCO is Short.

When I breakpoint in the Catch block, I can see the data has succefully persisted to the the db. It seems the problem is when the methods comes back and tries to set the new Id created into the POCO.

When I change the Id type in POCO to Int , it works.

Is this a bug ? what am I missing ?

Popular Answer

This looks like a bug an expectation. Here's the actual insert statement SqlMapperExtensions is using (around line 530):

var r = connection.Query("select @@IDENTITY id", transaction: transaction, commandTimeout: commandTimeout);
int id = (int)r.First().id; // (1)
if (keyProperties.Any())
        keyProperties.First().SetValue(entityToInsert, id, null); // (2)
return id;

You can see that the identity is expected to be an int (see (1) above). And then tries to set a property on the entity using the int value (see note (2) above). When your POCO's identity property is a short, the above will throw an exception.

Edit
As noted in the comments, Dapper.Contrib now supports the [Key] attribute.



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