Type Coercion - pengdows/pengdows.crud GitHub Wiki
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.
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
Coerce(value, dbFieldType, columnInfo, parseMode)
Coerce(value, sourceType, targetType)
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
If columnInfo.IsJsonType is true:
Deserializes string JSON into the target POCO type
Uses custom or default JsonSerializerOptions
Accepts:
String-formatted Guids (e.g., "742F...")
16-byte binary values
Converts string-formatted dates into UTC DateTime
Uses invariant culture
Assumes UTC and adjusts accordingly
Uses Convert.ChangeType for numeric/string coercion
Honors nullable target types
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