Type Coercion - pengdows/pengdows.crud GitHub Wiki

Table of Contents

TypeCoercionHelper

The TypeCoercionHelper class provides safe, database-aware type conversion between DbDataReader values and POCO property types. It is primarily used by EntityHelper during mapping and by pengdows.crud to normalize incoming data.

Purpose

Convert raw database values to correct .NET types

Handle enum string/number mapping

Parse JSON into complex POCOs when needed

Handle database quirks like stringified dates in MySQL or nonstandard Guid encodings

Entry Points

Coerce(value, dbFieldType, columnInfo, parseMode)

Coerce(value, sourceType, targetType)

Features

Enum Support

If a column is marked as an enum (via columnInfo.EnumType):

Attempts case-insensitive string match

If parsing fails, applies fallback based on EnumParseFailureMode:

Throw — throws an exception

SetNullAndLog — returns null and logs

SetDefaultValue — uses the first enum value

JSON Deserialization

If columnInfo.IsJsonType is true:

Deserializes string JSON into the target POCO type

Uses custom or default JsonSerializerOptions

Guid Support

Accepts:

String-formatted Guids (e.g., "742F...")

16-byte binary values

DateTime Support

Converts string-formatted dates into UTC DateTime

Uses invariant culture

Assumes UTC and adjusts accordingly

Safe Casting

Uses Convert.ChangeType for numeric/string coercion

Honors nullable target types

Example

Notes

Null or DBNull.Value returns null

Handles common real-world data issues (e.g., legacy schema, JSON-in-string)

Throws detailed InvalidCastException when conversion fails

Related Pages

EntityHelper

Supported Databases

SqlContainer

⚠️ **GitHub.com Fallback** ⚠️