![](/img/trans.png)
[英]Cannot deserialize string from BsonType ObjectId in MongoDb C#
[英]Cannot deserialize a 'String' from BsonType 'ObjectId'
我正在使用 mongoDb 开发一个 asp .net 核心项目。
我正在尝试通过 hotelCode 获得酒店。
HotelBedsContentService.cs
public async Task<HotelDocument> GetHotel(int code)
{
var x = await HotelCollection.Find(x => x.Code == code).FirstOrDefaultAsync();
return x;
}
通过这条线时,我得到了以下错误。 await _hotelBedsContentService.GetHotel(hotel.HotelCode);
System.FormatException: An error occurred while deserializing the Destination property of class TechneTravel.Domain.Documents.HotelBedsContents.HotelDocument: An error occurred while deserializing the Id property of class TechneTravel.Domain.Documents.HotelBedsContents.DestinationDocument: Cannot deserialize a 'String' from BsonType 'ObjectId'.
---> System.FormatException: An error occurred while deserializing the Id property of class TechneTravel.Domain.Documents.HotelBedsContents.DestinationDocument: Cannot deserialize a 'String' from BsonType 'ObjectId'.
---> System.FormatException: Cannot deserialize a 'String' from BsonType 'ObjectId'.
at MongoDB.Bson.Serialization.Serializers.StringSerializer.DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args)
...........
HotelDocument.cs
public class HotelDocument
{
public string Id { get; set; }
}
配置.cs
BsonClassMap.RegisterClassMap<HotelDocument>(cm =>
{
cm.AutoMap();
cm.SetIgnoreExtraElements(true);
cm.MapIdMember(c => c.Id).SetSerializer(new StringSerializer(BsonType.ObjectId)).SetIgnoreIfDefault(true);
});
为什么会出现这个错误? 我的配置有什么错误吗?
请帮我找出问题
看起来您的集合中的某些_id
无法转换为 ObjectId。 下面的代码运行良好:
// the below is not required, but it works with that too
//BsonClassMap.RegisterClassMap<HotelDocument>(cm =>
//{
// cm.AutoMap();
// cm.SetIgnoreExtraElements(true);
// cm.MapIdMember(c => c.Id).SetSerializer(new StringSerializer(BsonType.ObjectId)).SetIgnoreIfDefault(true);
//});
var id = ObjectId.GenerateNewId();
var client = new MongoClient();
var db = client.GetDatabase("d");
var coll = db.GetCollection<HotelDocument>("c");
coll.InsertOne(new HotelDocument() { Id = id.ToString() });
var result = coll.Find(c => c.Id == id.ToString()).ToList();
请提供触发您的问题的数据样本
MongoDB 仅在插入 ObjectId 类型时处理自动 id 生成。
如果要使用 string 或 int 或 long,则需要在插入之前设置 id。
您可以使用类似的方法检查数据一致性
HashSet<BsonType> inconsistentIds = new HashSet<BsonType>();
var cursor = await collection.Find(new BsonDocument()).Project(Builders<BsonDocument>.Projection.Include("_id")).ToCursorAsync();
foreach (BsonDocument doc in cursor.ToEnumerable())
inconsistentIds.Add(doc["_id"].BsonType);
Console.WriteLine($"There is {inconsistentIds.Count} id type");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.