Skip to content

Commit

Permalink
Fix Write IDictionary's with non string key type.
Browse files Browse the repository at this point in the history
  • Loading branch information
lanwin committed May 20, 2010
1 parent 5596d8e commit 9b58046
Showing 1 changed file with 15 additions and 4 deletions.
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace MongoDB.Configuration.DictionaryAdapters
{
Expand Down Expand Up @@ -36,14 +37,24 @@ public object CreateDictionary(Type valueType, Document document)
/// <returns></returns>
public Document GetDocument(object dictionary, Type valueType)
{
var type = typeof(KeyValuePair<,>).MakeGenericType(typeof(string), valueType);
var keyProperty = type.GetProperty("Key");
var valueProperty = type.GetProperty("Value");

if(dictionary==null)
return null;

var dictionaryType = dictionary.GetType();

if(!dictionaryType.IsGenericType)
throw new InvalidOperationException("Only generic IDictionary is supported");
if(dictionaryType.GetInterface(typeof(IDictionary<,>).FullName)==null)
throw new InvalidOperationException("Only generic IDictionary is supported");

var keyType = dictionaryType.GetGenericArguments().First();

var type = typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType);
var keyProperty = type.GetProperty("Key");
var valueProperty = type.GetProperty("Value");

var doc = new Document();

foreach (var e in (IEnumerable)dictionary)
doc.Add(keyProperty.GetValue(e, null).ToString(), valueProperty.GetValue(e, null));

Expand Down

0 comments on commit 9b58046

Please sign in to comment.