No mapping exists from DbType UInt64 to a known SqlDbType. Dapper C#

Viewed 1802

I have a table field(TotalPrice) in our SQL Server 2016 database with numeric(20, 3) data type.

I used ulong type as my C# property type.

public ulong TotalPrice { get; set; }

When I want to insert a record in my Table the following exception occurred.

No mapping exists from DbType UInt64 to a known SqlDbType

My C# code to insert a record:

const string queryInsertInvoice = @"
INSERT INTO Invoice (CustomerId, Number, TotalPrice, LatestStatusDateTime) 
VALUES (@CustomerId, @Number, @TotalPrice, @LatestStatusDateTime)
SELECT SCOPE_IDENTITY();";

var invoiceId = await dbConnection.QueryFirstOrDefaultAsync<int>(queryInsertInvoice, invoice);

How can I handle this situation with Dapper 2.0.53 ?

3 Answers

This is deliberate. SQL Server doesn't have unsigned integers, so it is trying to prevent you from storing the data as something different to what you expected - wraparound is fine for equality operations, but inequality operations would behave very unexpectedly for some values if we allowed this.

In other words: use long, not ulong.


Edit: I could be sold on the "Dapper should allow ulong for the first 63 bits - coercing it to long - and throw and exception (OverflowException?) if the MSB is set". That just isn't implemented today.

When I use Dapper what I do is create separate data classes from my main model that represent the results from SQL. With these SqlModel classes, I make sure the types align exactly with how things are represented in SQL. In my C# business logic, often it is easier to use int or enums for variables where they may be TINYINT in SQL. So I would end up with two classes like this:

class UserSqlModel {
  public string Name { get; set; }
  public byte UserTypeId { get; set; }
}

class User {
  public string Name { get; set; }
  public UserType Type { get; set; }
}

Then I would write a mapping function between the two models. This isolates your business logic from the nuances of how data is represented in SQL and allows refactoring your business logic or SQL implementation separately.

In your example, maybe your SqlModel would have a long property and your mapping function would handle conversion of ulong to long and would deal with overflow issues.

Related