Skip to content

Instantly share code, notes, and snippets.

@gregerhalltorp
Created February 17, 2012 15:06
Show Gist options
  • Save gregerhalltorp/1853953 to your computer and use it in GitHub Desktop.
Save gregerhalltorp/1853953 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