CanConvertFrom checks the DB Type
CanConvertTo checks the Model type.
CreateInstance should return an instance of the Model type.
Those three methods are called by the designer. The ConvertFrom/To are called at runtime.
So CanConvertFrom should check for Int32[]. It does. CanConvertTo should check for String, it checks for Int32[], so you have to change that.
So something like:
[Description("Converter for mapping a property with a .NET type string onto integer-array database column")]
public class StringArrayConverter : TypeConverter
{
public StringArrayConverter() { }
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType?.Equals(typeof(Int32[]));
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) => destinationType?.Equals(typeof(string));
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is int[] array)
{
return "{" + string.Join(",", array) + "}";
}
return null;
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
switch (value)
{
case null:
return null;
case string s when s.StartsWith("{") && s.EndsWith("}"):
s = s.Substring(1, s.Length - 2);
return s.Length > 0
? s.Split(',').Select(int.Parse).ToArray()
: Array.Empty<int>();
default:
return null;
}
}
public override object CreateInstance(ITypeDescriptorContext context, System.Collections.IDictionary propertyValues) => string.Empty;
}