0

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 ?

Yaron Levi
  • 12,535
  • 16
  • 69
  • 118

2 Answers2

1

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.

Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
  • It seems like you are right. It looks like a pretty big bug. I don't think defining an Int16 key is a corner case. It happens quite a lot. – Yaron Levi Oct 25 '14 at 22:00
  • I thought about this a bit and would actually consider this an "expectation" for using the dapper extension. – Metro Smurf Oct 26 '14 at 17:17
  • Seems quite odd to me. I can't see why they to put this limitation. – Yaron Levi Oct 26 '14 at 17:24
  • Another way to look at this is the extension also expects your entity to have a property named "Id"; they could have exposed an expression to allow a property named other than "Id". I do agree that this is a limitation; maybe you could contact the devs and see if they could add support for keys defined as other than `int`? – Metro Smurf Oct 27 '14 at 13:34
  • I added an issue in their GitHub page. Also, I am wating Marc Gravell will see this post and comment. – Yaron Levi Oct 27 '14 at 14:09
  • The Insert() method in Dapper Contrib actually supports the [Key] attribute to specify the identity property. – Johan Danforth Jun 07 '15 at 18:03
  • @JohanDanforth - thanks - I've updated the answer to accredit your comment. – Metro Smurf Jun 07 '15 at 19:15
0

The latest Dapper Contrib code now supports a short/Int16 identity property for inserts. The nuget package is not yet updated (as of june 7th -15) but will be shortly.

Johan Danforth
  • 4,469
  • 6
  • 37
  • 36