繁体   English   中英

mongoDB,使用C#官方驱动程序的强类型集合

[英]mongoDB, strongly typed collection using C# oficial driver

我正在学习MongoDB,并且想使用C#进行尝试。 是否可以使用C#官方MongoDB驱动程序对强类型的MongoDB文档进行操作?

我开设了AlbumPhoto课程:

public class Album : IEnumerable<Photo> 
    {
        [Required]
        [BsonElement("name")]
        public string Name { get; set; }

        [Required]
        [BsonElement("description")]
        public string Description { get; set; }

        [BsonElement("owner")]
        public string Owner { get; set; }

        [BsonElement("title_photo")]
        public Photo TitlePhoto { get; set; }

        [BsonElement("pictures")]
        public List<Photo> Pictures { get; set; }

        //rest of the class code
    }

public class Photo : IEquatable<Photo>
    {
        [BsonElement("name")]
        public string Name;

        [BsonElement("description")]
        public string Description;

        [BsonElement("path")]
        public string ServerPath;

        //rest of the class code
    }

我想在test数据库的收藏albums中插入一个新文档。 我不想在BsonDocument上进行操作,但是我更喜欢使用强类型的Album 我以为会是这样的:

IMongoClient client = new MongoClient();
IMongoDatabase db = client.GetDatabase("test");
IMongoCollection<Album> collection = database.GetCollection<Album>("album");
var document = new Album
            {
                Name = album.Name,
                Owner = HttpContext.Current.User.Identity.Name,
                Description = album.Description,
                TitlePhoto = album.TitlePhoto,
                Pictures = album.Pictures
            };
collection.InsertOne(document);

但这给了我以下错误:

MongoDB.Driver.Core.dll中发生类型为“ MongoDB.Driver.MongoCommandException”的异常,但未在用户代码中处理

附加信息:命令插入失败:解析字段文档::的元素0时出错:由::错误的'0'字段类型,预期对象,找到0:[]。

我在做什么错了,如果有可能实现呢?

看起来驱动程序将您的对象视为BSON数组,因为它实现了IEnumerable<Photo> 数据库期望使用BSON文档。 如果尝试将Int32插入到集合中,则会出现类似的错误。

不幸的是,我不知道如何配置序列化程序以将您的Album对象视为BSON文档。 静态BsonSerializer.SerializerRegistry属性显示驱动程序默认选择使用EnumerableInterfaceImplementerSerializer<Album,Photo>作为Album的序列化器。

Album删除IEnumerable<Photo>实现会导致驱动程序使用BsonClassMapSerializer<Album>进行序列化, BsonClassMapSerializer<Album>生成BSON文档。 虽然有效,但缺点是Album不再枚举; 应用程序使用者将需要枚举Pictures属性。

重新添加IEnumerable<Photo>实现,然后强制上述序列化程序(使用[BsonSerializer(typeof(BsonClassMapSerializer<Album>))]属性)将导致:

System.MissingMethodException:没有为此对象定义无参数的构造函数。

基于堆栈跟踪(请BsonSerializerAttribute.CreateSerializer ),消息所引用的对象似乎与序列化相关,而不是数据对象本身(我为两者都定义了无参数的构造函数)。 我不知道是否可以通过进一步的配置来解决此问题,或者驱动程序是否不允许以这种方式使用IEnumerable

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM