DapperLib / DapperLib/Dapper.Contrib

ISqlAdapter uses Convert.ChangeType for inserted Id which limits type conversion extensibility

Open
#123 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C#
Stars
293
Forks
109
PR merge metrics
No merged PRs in 30d

Description

Scenario described originally in https://github.com/andrewlock/StronglyTypedId/issues/43

To summarize I have a custom struct to represent an Id field of an entity. The struct has a TypeConverter as well as a DapperTypeHandler to handle conversions to/from int but due to the implementation of MySqlAdapter (and other ISqlAdapters) this Id field can't be used naturally with Dapper.Contrib's InsertAsync.

The problem arises as mysql's LAST_INSERT_ID() returns a ulong and Dapper.Contrib uses Convert.ChangeType to convert the resulting ulong into the target field.

One solution would be to use Dapper's existing mechanisms for mapping fields (TypeHandler) but that doesn't seem to have a public API so I'm not sure how that would be achieved.

Alternatively, the MySqlAdapter (and other ISqlAdapters) can be changed to use something like the following

var converter = TypeDescriptor.GetConverter(typeof(idp.PropertyType));
var newValue = converter.ConvertFrom(id);
idp.SetValue(entityToInsert, newValue, null);

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 with SqlMapperExtensions.cs at the Convert.ChangeType call around line 945, then inspect MySqlAdapter and the other ISqlAdapter implementations. Reproduce the custom struct scenario where MySQL LAST_INSERT_ID() returns ulong, and compare the available TypeConverter and Dapper type-handling paths. Done means InsertAsync can assign custom ID types without restricting conversion to Convert.ChangeType.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, mysql
Domain
databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.