簡體   English   中英

使用 MongoDB C# 驅動程序將 null 讀入可為 null 的 int

[英]Reading null into a nullable int with MongoDB C# driver

我的 MongoDB 中有數據,我在其中存儲了一個可為空的 int,通常為 null。 我在 C# 端的模型的變量為int? MaterialID int? MaterialID

當我運行.Query.FirstOrDefault() ,出現錯誤“輸入字符串的格式不正確”。 每當它嘗試從 Mongo 讀取空值時(整數工作正常)。

我設法通過改變我的 int 來解決這個問題? 到一個字符串,然后再將它轉換回一個 int?,但這是一個我真的不喜歡的可怕的黑客。 任何人對我如何從 Mongo 讀取 null 到我的 int 有任何想法? 在 C# 方面?

謝謝。

我的JSON:

 "Collection" : { "List" : [ { "ID" : "40", "StartDate" : ISODate("2013-01-01T00:00:00.000Z"), "EndDate" : ISODate("2013-12-31T00:00:00.000Z"), "MaterialID" : "3" }, { "ID" : "40", "StartDate" : ISODate("2014-01-01T00:00:00.000Z"), "EndDate" : ISODate("2014-09-30T00:00:00.000Z"), "MaterialID" : "null" } ]

您將 MaterialID 字段作為字符串存儲在數據庫中(類型 2)。 當然,當您嘗試將字符串值分配給可為空的整數時,您會出錯。 注意:即使null也存儲為帶有文本"null"字符串。 我建議您從修復數據庫中的數據開始。 您可以從 mongo shell 執行此操作:

> db.collection.find({MaterialID:{$type:2}}).forEach(
    function(doc){ 
       var materialId = (doc.MaterialID == "null") ? null : new NumberInt(doc.MaterialID);
       db.collection.update({_id:doc._id},{$set:{MaterialID: materialId}});
    })

注意:在您的 json 文檔中沒有 _id 字段,但我認為它在那里而不是 ID 字段。 無論如何,您可以根據需要調整腳本。

更改字段類型后,您到可為空 int 的映射將正常工作。


順便說一句,如果由於某種原因您無法修復數據庫中的數據,還有另一種選擇。 您可以使用自定義 BSON 序列化程序來轉換 int? 字符串,反之亦然:

public class NullableIntAsStringSerializer : SerializerBase<int?>
{
    public override void Serialize(
        BsonSerializationContext context, BsonSerializationArgs args, int? value)
    {
        context.Writer.WriteString(value.HasValue ? value.ToString() : "null");
    }

    public override int? Deserialize(
        BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var str = context.Reader.ReadString();
        return str == "null" ? (int?)null : Int32.Parse(str);
    }
}

並將此序列化程序分配給您的財產

[BsonSerializer(typeof(NullableIntAsStringSerializer))]
public int? MaterialID { get; set; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM