Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

Proposal: Add Support for Loosely Coupled Custom Query Parameter

Open robert-io opened this issue 3 years ago • 0 comments

With the ICustomQueryParameter we are able to create custom datatypes and control how the ADO.Net parameter is created and configured, this allows for a seamless coding experience.

I would like to expand on this functionality a little and add support for a loosely coupled custom query parameter. For this to work Dapper would use a Duck Typing technique and look for a method with the following exact instance level signature and use that to add the ADO.Net Parameter:

  • AddParameter(IDbCommand, string)

If the existing ICustomQueryParameter interface is implemented this will take priority. The AddParameter method can be public, internal or private, this will allow the assembly developer to expose only the type functionality they are working on and support Dapper.

The motivation for a loosely coupled custom query parameter is to be able to support dapper with custom types without having to reference Dapper, dragging it along in projects that don't need it. Some projects have no Data Store requirement.

The following is what i have in mind, this would go immediately after the ICustomQueryParameter code:

var addParameterMethod = prop.PropertyType.GetMethod(nameof(ICustomQueryParameter.AddParameter), BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, new[] { typeof(IDbCommand), typeof(string) }, null);
if (addParameterMethod is not null)
{
	il.Emit(OpCodes.Ldloc, typedParameterLocal); // stack is now [parameters] [typed-param]
	il.Emit(callOpCode, prop.GetGetMethod()); // stack is [parameters] [custom]
	il.Emit(OpCodes.Ldarg_0); // stack is now [parameters] [custom] [command]
	il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [custom] [command] [name]
	il.EmitCall(OpCodes.Callvirt, addParameterMethod, null); // stack is now [parameters]
	continue;
}

robert-io avatar Jul 05 '22 05:07 robert-io