无法应对A' String'来自bsontype' objectid'

发布于 2025-02-01 19:52:18 字数 1751 浏览 3 评论 0原文

我正在使用MongoDB进行ASP .NET核心项目。

我正在尝试通过酒店码来获得酒店。

hotelbedscontentservice.cs

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

经过这条线时,我的错误低于错误。 等待_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; }
}

configuration.cs

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

            });

为什么会发生此错误?我的配置有任何错误吗?

请帮助我找到问题

I am working a asp .net core project with mongoDb.

I am trying to get hotel by hotelCode.

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

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

Configuration.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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

韵柒 2025-02-08 19:52:18

收藏集中的某些_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();

请提供触发您的问题的数据示例

It looks like some _id in your collection cannot be converted to 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

若无相欠,怎会相见 2025-02-08 19:52:18

MongoDB仅在ObjectID类型上插入时处理自动ID生成。

如果要使用字符串或int或长时间,则需要在插入之前设置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/main/dotnet/02%20-%20-%20-intermediate/checkidconsistency.cs

MongoDB handles automatic id generation on Insert for ObjectId type only.

If you want to use string or int or long then you need to set the id before you insert.

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(
quot;There is {inconsistentIds.Count} id type");

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文