Skip to content

Support reading of custom types #115

Open
@samcragg

Description

@samcragg

Would you accept a PR to allow reading of custom types?

Background

In my app I often wrap primitive types in dedicated types to express exactly what they represent and prevent the wrong values being passed around. I spotted there's a TypeHandler class that looks promising, but currently unused.

Proposal

Add a method to TypeHandler that accepts the reader, default implemented to match current behaviour (i.e. non breaking change)

public virtual T Read(DbDataReader reader, int fieldOffset)
        => CommandUtils.As<T>(reader.GetValue(fieldOffset));

Modify the code generator to spot where the TypeHandlerAttribute has been used and, when reading a value that matches:

  • Change the Tokenize to skip the type check when reading the custom type (it's never going to come back from the DB as that type - if it does the type handler can still do the check)
  • Change the generated Read method to create the type handler and invoke the Read method on it.
  • Implement the reading/writing of parameters that are also on the TypeHandler class (it looks like it's not yet implemented)

Alternatively, as it looks like TypeHandler isn't yet used, we could make it an interface with static virtual methods, which would be a micro-optimization that avoids needing to create an instance of the handler when reading the values (i.e. we could write CustomTypeHandler.Read instead of new CustomTypeHandler().Read(), saving an allocation)

I'd be happy to do the work myself and submit a PR (with appropriate tests and some documentation on how to use it), just wanted confirmation this is the right approach to take or if there were any other plans to bring across the SqlMapper type functionality across.

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions