Skip to content

Data Type Conversion

Max Stepanskiy edited this page Mar 31, 2021 · 8 revisions

Sometimes a developer is posed with a problem of data type mismatch between a .NET type and ADO.NET supported types (or even underlying column type). For example, a column which contains NULL may not map easily to an int property. That's why Nemo provides various data conversion attributes a developer can declare on a property of a DTO in order to make mapping smoother. Another way to deal with most of the type mismatch issues would be to enable AutoTypeCoercion on a given Nemo.Configuration.IConfiguration instance. However, type coercion will not work for delimited string to list conversion, XML data or UTC date/time conversion. Those will require explicit type converter declaration.

A developer can provide custom conversion by implementing ITypeConverter<TFrom, TTo> interface or by chaining multiple conversions using CompositeConverter.

Here are basic examples on how to utilize type converters using annotations. Another way to set a converter is to use EntityMap<T> and call WithTransform method to provide an appropriate type converter for a given property. See more here.

public class Order 
{
    public int OrderId { get; set; }
    ...
    [TypeConverter(typeof(DBNullableTypeConverter<DateTime>))]
    public DateTime? ShippingDate { get; set; }
}

DBNull mapping to strings is handled similarly:

public class Customer 
{
    public string CustomerId { get; set; }
    ...
    [TypeConverter(typeof(DBNullableStringConverter))]
    public string CompanyName { get; set; }
}

It is also easy to convert comma-delimited text values into a list:

public class Customer
{
    public string CustomerId { get; set; }
    ...
    [TypeConverter(typeof(ListConverter<int>))]
    public List<int> OrderIdList { get; set; }
}

Clone this wiki locally