MongoDb C# driver, property of type implementing IList not saving

僤鯓⒐⒋嵵緔 提交于 2019-12-13 05:08:57

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/4778841/mongodb-c-sharp-driver-property-of-type-implementing-ilist-not-saving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!