MongoDB(C#驱动程序)反序列化ObjectID字段时出现问题
我使用MongoDB将文档反序列化为C#对象,但ObjectID字段有问题。这就是我得到的错误: MyProject.Data.MyDocument类的属性“LayoutId”缺少必需的元素“LayoutId” 由于指定了LayoutId字段,因此该字段(如果看起来不奇怪)是有意义的:MongoDB(C#驱动程序)反序列化ObjectID字段时出现问题,c#,mongodb,mongodb-.net-driver,C#,Mongodb,Mongodb .net Driver,我使用MongoDB将文档反序列化为C#对象,但ObjectID字段有问题。这就是我得到的错误: MyProject.Data.MyDocument类的属性“LayoutId”缺少必需的元素“LayoutId” 由于指定了LayoutId字段,因此该字段(如果看起来不奇怪)是有意义的: using System; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace MyProject.Data {
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace MyProject.Data
{
public class MyDocument
{
public override ObjectId Id { get; set; }
[BsonRequired]
public String Name { get; set; }
[BsonRequired]
public ObjectId LayoutId { get; set; }
}
}
并将其填充到数据库中:
那么,序列化过程的哪些其他方面可以防止填充此元素呢?特定版本的驱动程序中是否存在bug?我是否使用了正确的数据类型
还应指出的是:
- 此文档用于在数据库中填充该值,因此似乎只有反序列化是一个问题,序列化是可以的
- 同一个库中还有其他具有相同版本的文档
- 同一解决方案中存在mongo文档/合同,但在不同的库中,这些文档/合同似乎没有相同的prolem
- 我无法重现此错误。你能用测试程序更新你的问题吗
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace TestConsole_Source
{
class Program
{
public class MyDocument
{
public ObjectId Id { get; set; }
[BsonRequired]
public string Name { get; set; }
[BsonRequired]
public ObjectId LayoutId { get; set; }
}
static void Main(string[] args)
{
var server = MongoServer.Create();
server.Connect();
var db = server.GetDatabase("docstest");
var collection = db.GetCollection<MyDocument>("docs");
collection.Drop();
var doc = new MyDocument
{
Name = "Test",
LayoutId = ObjectId.GenerateNewId()
};
collection.Save(doc);
var foundDoc = collection.FindOne();
//Console.ReadKey();
}
}
}
使用MongoDB.Bson;
使用MongoDB.Bson.Serialization;
使用MongoDB.Bson.Serialization.Attributes;
使用MongoDB.Driver;
使用System.Collections.Generic;
使用System.Collections.ObjectModel;
使用System.Linq;
命名空间TestConsole\u源
{
班级计划
{
公共类MyDocument
{
公共对象Id{get;set;}
[b必须填写]
公共字符串名称{get;set;}
[b必须填写]
public ObjectId LayoutId{get;set;}
}
静态void Main(字符串[]参数)
{
var server=MongoServer.Create();
Connect();
var db=server.GetDatabase(“docstest”);
var collection=db.GetCollection(“文档”);
collection.Drop();
var doc=新的MyDocument
{
Name=“Test”,
LayoutId=ObjectId.GenerateNewId()
};
收款.保存(单据);
var foundDoc=collection.FindOne();
//Console.ReadKey();
}
}
}
感谢克雷格尝试解决这个问题。原来我没有把问题写好
问题是我对结果调用了“SetFields()”,而我请求的字段不包括“LayoutId”。不过,我希望驱动程序会出现更具描述性的错误。如果您正确地从LayoutId中删除了BsonRequired属性,问题是否会消失?@CraigWilson如果我这样做,则字段将保持为空。因此,在反序列化过程中,BSON字段与class字段不匹配。您的示例代码可以很好地加载文档。我可能要补充的是,还有其他包含对象id的文档可以正常工作,因此可能有一些与mongo无关的内容导致文档反序列化失败。不确定您想要哪种类型的更好的错误消息。它特别提到LayoutId失踪。你有更好的错误消息建议吗?@CraigWilson驱动程序知道你反序列化到哪个类,它知道你请求的字段。因此,类似于“字段列表中指定的字段缺少必需字段”的内容可能更有用。