Question

Changed the persistence layer of my web app to MongoDb using the C# drivers from the MongoDb site. Was pleasantly surprised to find all of my tests passing... except for one class. One of its properties is a type that implements IList and for some reason it doesn't save its items.

I've built a minimal test case to illustrate. Here's the test code to create and save the parent object:

var fooCollection = database.GetCollection<Foo>( typeof( Foo ).Name );
var foo = new Foo {Id = "Root"};
foo.Foos.Add( new Foo{ Id = "Child" } );
fooCollection.Save( foo );

If I declare Foo.Foos as being List<Foo> it works:

public class Foo {
  public Foo() {
    Foos = new List<Foo>();
  }
  public List<Foo> Foos;
  public string Id;
}  

The (correct) result:

{ "_id" : "root", "Foos" : [ { "Foos" : [], "_id" : "child" } ] }

However what I need is this:

public class Foo {
  public Foo() {
    Foos = new FooList();
  }
  public FooList Foos;
  public string Id;
}

public class FooList : IList<Foo> {
   //IList implementation omitted for brevity
}

The (incorrect) result is:

{ "_id" : "root", "Foos" : { "Capacity" : 4 } }

Note that it has nothing to do with my IList implementation as the results are the same if I use FooList : List<Foo>.

I'm presuming that the BSON serializer is getting confused? I looked at the documentation on discriminators, which led me to think that this might help:

BsonClassMap.RegisterClassMap<List<Foo>>( cm => {
  cm.AutoMap();
  cm.SetIsRootClass( true );
} );
BsonClassMap.RegisterClassMap<FooList>();    

I still don't get my items saved though, ends up looking like this:

{ "_id" : "root", "Foos" : { "_t" : [ "List`1", "FooList" ], "Capacity" : 4 } }

How can I save FooList correctly?

Was it helpful?

Solution

I am able to reproduce what you are describing with 0.9, but it is working correctly with the latest code.

You could build the driver yourself from the latest code in github, or wait for 0.11 which is coming it very soon.

-- Robert Stam, on the monodb-user Google Group

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top