Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nathan130200/83c55446e9adc17ee2030d08a99eaa61 to your computer and use it in GitHub Desktop.
Save nathan130200/83c55446e9adc17ee2030d08a99eaa61 to your computer and use it in GitHub Desktop.
Custom type converter for converting between MongoDB.Bson.ObjectId and string
public class ObjectIdConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value)
{
if (value is string)
return MongoDB.Bson.ObjectId.Parse((string)value);
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context,
Type destinationType)
{
if (destinationType == typeof(string))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value,
Type destinationType)
{
if (destinationType == typeof(string))
return ((MongoDB.Bson.ObjectId)value).ToString();
return base.ConvertTo(context, culture, value, destinationType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment