SmartEnum and Dapper
- Dominant language
- C#
- Stars
- 2.4k
- Forks
- 184
- PR merge metrics
- No merged PRs in 30d
Description
Hi,
I wrote a generic custom typehandler for SmartEnums and Dapper ORM. It will save the int value of the SmartEnum to the database and convert it back to the relevant SmartEnum when reading from the database.
using Ardalis.SmartEnum;
using Dapper;
using System;
using System.Data;
public class SmartEnumHandler : SqlMapper.TypeHandler where T : SmartEnum
{
public override T Parse(object value)
{
return SmartEnum.FromValue(Convert.ToInt32(value));
}
public override void SetValue(IDbDataParameter parameter, T smartEnumeration)
{
parameter.Value = smartEnumeration.Value;
}
}
I am using autofac to containerize my application, but cannot find the right syntax to register the SmartEnumHandler for all SmartEnums I created. Instead, in the container setup I register a handler for each SmartEnum individually, i.e:
SqlMapper.AddTypeHandler(new SmartEnumHandler());
SqlMapper.AddTypeHandler(new SmartEnumHandler());
Any suggestion on how to register the TypeHandler for all SmartEnums in one line would be greatly appreciated.
Feel free to include the generic method in your nuget package if it is of any use to you.
Using VS2019 Community Edition, C#, .Net Core 3, Dapper -> latest NuGet.
Niels
Contributor guide
Research direction
Start with the SmartEnumHandler example in the issue and the Dapper SqlMapper.AddTypeHandler calls, then inspect how SmartEnum types are discovered and how Autofac registrations are configured. Determine whether a supported registration path can cover all SmartEnum types, and verify that values round-trip correctly between SmartEnum instances and database parameters.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- databases
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100