简体   繁体   English

无法从 BsonType 'ObjectId' 反序列化 'String'

[英]Cannot deserialize a 'String' from BsonType 'ObjectId'

I am working a asp .net core project with mongoDb.我正在使用 mongoDb 开发一个 asp .net 核心项目。

I am trying to get hotel by hotelCode.我正在尝试通过 hotelCode 获得酒店。

HotelBedsContentService.cs HotelBedsContentService.cs

public async Task<HotelDocument> GetHotel(int code)
        {
            var x = await HotelCollection.Find(x => x.Code == code).FirstOrDefaultAsync();
            return x;
        }

When passing this line, I got below error.通过这条线时,我得到了以下错误。 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 HotelDocument.cs

public class HotelDocument
{
    public string Id { get; set; }
}

Configuration.cs配置.cs

BsonClassMap.RegisterClassMap<HotelDocument>(cm =>
            {
                cm.AutoMap();
                cm.SetIgnoreExtraElements(true);
                cm.MapIdMember(c => c.Id).SetSerializer(new StringSerializer(BsonType.ObjectId)).SetIgnoreIfDefault(true);

            });

Why this error occurs?为什么会出现这个错误? Is there any mistake in my configuration?我的配置有什么错误吗?

Please help me find the issue请帮我找出问题

It looks like some _id in your collection cannot be converted to ObjectId.看起来您的集合中的某些_id无法转换为 ObjectId。 The below code works well:下面的代码运行良好:

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

please provide a data sample that trigger your issue请提供触发您的问题的数据样本

MongoDB handles automatic id generation on Insert for ObjectId type only. MongoDB 仅在插入 ObjectId 类型时处理自动 id 生成。

If you want to use string or int or long then you need to set the id before you insert.如果要使用 string 或 int 或 long,则需要在插入之前设置 id。

You can check your data consistency with something like您可以使用类似的方法检查数据一致性

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

https://github.com/iso8859/learn-mongodb-by-example/blob/main/dotnet/02%20-%20Intermediate/CheckIdConsistency.cs https://github.com/iso8859/learn-mongodb-by-example/blob/main/dotnet/02%20-%20Intermediate/CheckIdConsistency.cs

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

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