CommaSeparatedStringToStringArrayPropertyHandler
A property handler that maps a comma-separated string column, such as the MySQL SET type, into a string array property.
A property handler that maps a comma-separated string column (for example, the MySQL SET type) into a string array property.
The members are neither trimmed nor otherwise altered. To map a
SETcolumn into a[Flags]enumeration instead, use StringToEnumPropertyHandler.
Overview
| Name | Description |
|---|---|
| Class | CommaSeparatedStringToStringArrayPropertyHandler |
| Namespace | RepoDb.PropertyHandlers |
| Package | RepoDb |
| Implements | IPropertyHandler<string, string[]> |
| Column type | A comma-separated string column (for example, the MySQL SET type) |
| Property type | string[] |
Conversions
| Method | Direction | Description |
|---|---|---|
| Get | Database to property | Splits the value returned by the database on the comma. An empty string is returned as an empty array and a null value is returned as null. |
| Set | Property to database | Joins the array into a comma-separated value. A null array is written as null. |
Exceptions
| Exception | Thrown When |
|---|---|
ArgumentException |
A member of the array being written contains a comma, as it cannot be represented in the comma-separated value. |
Usability
Bind the handler to the property that maps to a SET column.
Attribute
public class Account
{
public int Id { get; set; }
[Map("roles"), PropertyHandler(typeof(CommaSeparatedStringToStringArrayPropertyHandler))]
public string[] Roles { 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, Roles = new[] { "Read", "Write" } });
var account = connection.Query<Account>(e => e.Id == 1).First();
// account.Roles is { "Read", "Write" }; the column holds Read,Write
}
Fluent Mapping
To configure via FluentMapper:
FluentMapper
.Entity<Account>()
.PropertyHandler<CommaSeparatedStringToStringArrayPropertyHandler>(e => e.Roles);
Property Level Mapping
To configure via PropertyHandlerMapper:
PropertyHandlerMapper.Add<Account, CommaSeparatedStringToStringArrayPropertyHandler>(e => e.Roles, new CommaSeparatedStringToStringArrayPropertyHandler(), true);
Type Level Mapping
To apply the handler to every property of the type string[]:
PropertyHandlerMapper.Add<string[], CommaSeparatedStringToStringArrayPropertyHandler>(new CommaSeparatedStringToStringArrayPropertyHandler(), true);
A type level mapping is process-wide: it is applied to every
string[]property of every entity and connection, not only to the intended column. Prefer the attribute, fluent or property level mapping unless everystring[]property maps to a comma-separated string column.