2016-12-07 1 views
1

を変更:MongoDb.Driver 2.4 deserilizationデータ型Iは、以下のPOCOクラスを持っている

class MyClass { 
    public Objectid _id {get;set;} 
    public string property1 {get;set;} 
    public string property2 {get;set;} 
    public int property3 {get;set;} 
} 

オブジェクトは、MongoDBのコレクションに格納されます。 が逆シリアル化できません:直列化復元することができませんでした

var items = db.GetCollection<MyClass>("MyClass").AsQueryable().Select(x => x.property1 == "SomeString").ToList(); 

私はそのproperty2ことを示すエラーが表示されます。

property1: "SomeString" 
property2: "12345" 
property3: 98765 

私がコレクションを照会しようとします。データは、得られたBSONで正しいデータ型を持っていますBsonType「Int64型」から「文字列」

私は自分のオブジェクトに文字列値にDBでBSON文書から文字列値をデシリアライズしようとしています。

はなぜBsonSerializerは小数に変換しようとしていますか?この例では、値は数値であるが、値は通常英数字であるため、フィールドはクラス内で文字列として定義されている。

私はVS2013で、MongoDb.DriverのV2.4パッケージを使用しています。あなたがそのプロパティに対して独自のシリアライザを記述する必要がMongoのプロパティタイプの変更については

+0

コレクション 'property2'の 'MyClass'には、タイプがint64の値が含まれています。 Mongoコンソールで直接javascriptを使用してデータ型を更新することができます。私はC#のドライバは、同じ機能をサポートしていないと思う。 – rnofenko

答えて

0

これが本来の目的である、あなたはモンゴに、これらのオブジェクトのいくつかを保存しています。

public class TestingObject 
{ 
    public string FirstName { get; set; } 

    public string LastName { get; set; } 

    public int TestingObjectType { get; set; } 
} 

今、私たちは、これはあなたがそれから得る

をデシリアライズすることはできませんでしょう

public class TestingObject 
{ 
    public string FirstName { get; set; } 

    public string LastName { get; set; } 

    public string TestingObjectType { get; set; } 
} 

私たちの新しいクラスである文字列

にint型からTestObjectTypeを変更する必要がありますBsonType 'Int64'の 'String'

必要なのは、変換を処理するシリアライザです。

public class TestingObjectTypeSerializer : IBsonSerializer 
{ 
    public Type ValueType { get; } = typeof(string); 

    public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) 
    { 
     if (context.Reader.CurrentBsonType == BsonType.Int32) return GetNumberValue(context); 

     return context.Reader.ReadString(); 
    } 

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value) 
    { 
     context.Writer.WriteString(value as string); 
    } 

    private static object GetNumberValue(BsonDeserializationContext context) 
    { 
     var value = context.Reader.ReadInt32(); 

     switch (value) 
     { 
      case 1: 
       return "one"; 
      case 2: 
       return "two"; 
      case 3: 
       return "three"; 
      default: 
       return "BadType"; 
     } 
    } 
} 

重要な部分は、デシリアライズ方式です。型がint32の場合のみ、変換ロジックを実行しますか?型が何か他のものであれば、それは既に文字列であり、その値を返すと仮定します。

Serializeをちょうど出てWriteStringメソッドと、任意のドキュメント更新または保存されたいずれかの文字列として、新たな価値を持つことになります。

は今、あなたはちょうどあなたがエラーを取得するべきではありませんあなたのシリアライザにあなたがモンゴからそれを読ん

public class TestingObject 
{ 
    public string FirstName { get; set; } 

    public string LastName { get; set; } 

    [BsonSerializer(typeof(TestingObjectTypeSerializer))] 
    public string TestingObjectType { get; set; } 
} 

次の時間を使用するようにプロパティを伝えるために、あなたのオブジェクトを更新する必要があります。

関連する問題