BitToByteArrayPropertyHandler

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

A property handler that maps a multi-bit database column (for example, the MySQL BIT(n) type) into a byte array property, in big-endian order.

The width of the column is not known to the handler. The array is always 8 bytes long, regardless of the n of BIT(n).

Overview

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

Conversions

Method Direction Description
Get Database to property Converts the value returned by the driver into a big-endian byte[]. The array is always 8 bytes long, with leading zero bytes for the unused high bits. null and DBNull are returned as null.
Set Property to database Converts the big-endian byte[] into an ulong. A null array is written as null.

Exceptions

Exception Thrown When
ArgumentException The array being written, 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(BitToByteArrayPropertyHandler))]
    public byte[] Flags { 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 Permission { Id = 1, Flags = new byte[] { 0, 0, 0, 0, 0, 0, 0, 9 } });
    var permission = connection.Query<Permission>(e => e.Id == 1).First();
    // permission.Flags is { 0, 0, 0, 0, 0, 0, 0, 9 }
}

Fluent Mapping

To configure via FluentMapper:

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

Property Level Mapping

To configure via PropertyHandlerMapper:

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

Type Level Mapping

To apply the handler to every property of the type byte[]:

PropertyHandlerMapper.Add<byte[], BitToByteArrayPropertyHandler>(new BitToByteArrayPropertyHandler(), true);

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

See Also