MongoDb C#驱动程序,实现IList的类型的属性未保存 [英] MongoDb C# driver, property of type implementing IList not saving

查看:50
本文介绍了MongoDb C#驱动程序,实现IList的类型的属性未保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用MongoDb站点上的C#驱动程序将我的Web应用程序的持久层更改为MongoDb.惊喜地发现我所有的测试都通过了……除了一堂课.它的属性之一是实现IList的类型,由于某种原因,它不保存其项目.

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 );

如果我将Foo.Foos声明为List<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;
}  

(正确的)结果:

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

但是我需要的是

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

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

(不正确的)结果是:

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

请注意,这与我的IList实现无关,因为如果使用FooList : List<Foo>,结果是相同的.

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

我以为BSON序列化程序会变得混乱?我查看了有关歧视者的文档,这使我认为这可能有所帮助:

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 } }

如何正确保存FooList?

推荐答案

我能够重现你的身份 用0.9进行描述,但是可以正常工作 正确使用最新代码.

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

您可以自己构建驱动程序 来自github中的最新代码,或者 等待0.11即将到来 很快.

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,位于 monodb用户Google网上论坛

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

这篇关于MongoDb C#驱动程序,实现IList的类型的属性未保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆