DapperLib / DapperLib/Dapper

InvalidCastException - Converting DB type Int64 to C# IComparable

Open
#1,207 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature request
Dominant language
C#
Stars
18.4k
Forks
3.7k
Avg merge
5h 8m
Merged PRs (30d)
1

Description

I'm having an issue where I'm trying to query integer data and populate it onto a property of type IComparable. The exception that occurs is:

{System.InvalidCastException: Invalid cast from 'System.Int64' to 'System.IComparable'. at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)}

The best I can tell, there's an issue with the IL emitted code in SqlMapper.FlexibleConvertBoxedFromHeadOfStack where it's falling back to a System.Convert.ChangeType() call if it didn't successfully handle the type conversion earlier in the method. An additional else if condition to check if the to type is assignable from the from type and casting directly to the to type appears to resolve the bug. I put a commit together at https://github.com/bhasden/Dapper/commit/135a30b71f03a0830024f397de5f20b76271ba07 that resolves the issue for my scenario. I'm happy to submit a PR if this is an acceptable fix. I have a test project that I can convert to a unit test as well. Any feedback is greatly appreciated.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at SqlMapper.FlexibleConvertBoxedFromHeadOfStack and reproduce the Int64-to-IComparable mapping scenario described in the issue. Review the linked commit for the proposed conversion behavior, then convert the reporter's test project into a unit test. Done means the query maps the database integer to an IComparable property without InvalidCastException.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.