BitToBitArrayPropertyHandler

A property handler that maps a multi-bit database column, such as the MySQL BIT(n) type, into a BitArray property.

A property handler that maps a multi-bit database column (for example, the MySQL BIT(n) type) into a BitArray property.

The width of the column is not known to the handler. The BitArray is always 64 bits long and the unused high bits are false, so do not rely on Length to match the n of BIT(n).

Overview

Name Description
Class BitToBitArrayPropertyHandler
Namespace RepoDb.PropertyHandlers
Package RepoDb
Implements IPropertyHandler<object, BitArray>
Column type A multi-bit column (for example, the MySQL BIT(n) type)
Property type BitArray

Conversions

Method Direction Description
Get Database to property Converts the value returned by the driver (an ulong, a big-endian byte[], a bool, or any value convertible to ulong) into a BitArray of 64 bits, where the index 0 is the least significant bit. null and DBNull are returned as null.
Set Property to database Converts the BitArray into an ulong, where the index 0 is the least significant bit. A null value is written as null.

Exceptions

Exception Thrown When
ArgumentException The BitArray being written is longer than 64 bits, or a byte[] returned by the driver is longer than 8 bytes.

Usability

Bind the handler to the property that maps to a BIT(n) column.

Attribute

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

    [Map("flags"), PropertyHandler(typeof(BitToBitArrayPropertyHandler))]
    public BitArray Flags { get; set; }
}

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

using (var connection = new MySqlConnection(connectionString))
{
    var flags = new BitArray(8);
    flags[0] = true; // the least significant bit
    flags[3] = true;

    connection.Insert(new Permission { Id = 1, Flags = flags });
    var permission = connection.Query<Permission>(e => e.Id == 1).First();
    // permission.Flags has 64 bits; the bits 0 and 3 are set
}

Fluent Mapping

To configure via FluentMapper:

FluentMapper
    .Entity<Permission>()
    .PropertyHandler<BitToBitArrayPropertyHandler>(e => e.Flags);

Property Level Mapping

To configure via PropertyHandlerMapper:

PropertyHandlerMapper.Add<Permission, BitToBitArrayPropertyHandler>(e => e.Flags, new BitToBitArrayPropertyHandler(), true);

Type Level Mapping

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

PropertyHandlerMapper.Add<BitArray, BitToBitArrayPropertyHandler>(new BitToBitArrayPropertyHandler(), true);

See Also