簡體   English   中英

無法從 BsonType 'ObjectId' 反序列化 'String'

[英]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");

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