StringToEnumPropertyHandler

A property handler that maps a string-based column, such as the MySQL ENUM and SET types, into an enumeration property.

A property handler that maps a string-based database column (for example, the MySQL ENUM type, or the MySQL SET type when used with a [Flags] enumeration) into a TEnum property.

The TEnum type argument is constrained to struct, Enum.

Overview

Name Description
Class StringToEnumPropertyHandler<TEnum>
Namespace RepoDb.PropertyHandlers
Package RepoDb
Implements IPropertyHandler<string, TEnum>
Column type A string-based column (for example, the MySQL ENUM type, or the MySQL SET type with a [Flags] enumeration)
Property type TEnum

Conversions

Method Direction Description
Get Database to property Converts the string into a TEnum by member name, ignoring the casing. A comma-separated list of names is combined when TEnum is a [Flags] enumeration. A null, empty or white-space value is returned as default.
Set Property to database Converts the TEnum into its member name. The names of a [Flags] enumeration are joined by a comma without spaces (for example Read,Write), which is the format of the MySQL SET type.

Usability

Bind the handler, closed over the enumeration, to the property that maps to an ENUM or SET column. For a SET column, decorate the enumeration with [Flags].

Attribute

public class Account
{
    public int Id { get; set; }

    [Map("role"), PropertyHandler(typeof(StringToEnumPropertyHandler<Role>))]
    public Role Role { get; set; }
}

Once bound, the library invokes the handler automatically when the property is read or written.

using (var connection = new MySqlConnection(connectionString))
{
    connection.Insert(new Account { Id = 1, Role = Role.Admin | Role.Editor });
    var account = connection.Query<Account>(e => e.Id == 1).First();
    // the SET column holds Admin,Editor
}

Fluent Mapping

To configure via FluentMapper:

FluentMapper
    .Entity<Account>()
    .PropertyHandler<StringToEnumPropertyHandler<Role>>(e => e.Role);

Property Level Mapping

To configure via PropertyHandlerMapper:

PropertyHandlerMapper.Add<Account, StringToEnumPropertyHandler<Role>>(e => e.Role, new StringToEnumPropertyHandler<Role>(), true);

Type Level Mapping

To apply the handler to every property of the type Role:

PropertyHandlerMapper.Add<Role, StringToEnumPropertyHandler<Role>>(new StringToEnumPropertyHandler<Role>(), true);

A type level mapping is process-wide: it is applied to every Role property of every entity and connection, not only to the intended column. Prefer the attribute, fluent or property level mapping unless every Role property maps to a ENUM or SET column.

The handler is closed over a single enumeration. A type level mapping only affects that enumeration and does not apply to the other enumeration types.

See Also