简体   繁体   中英

MongoDB Custom Serializer not setting properties

Whenever using a custom serializer it sets the property value correctly in the database but the property on the object remains the default value.

Custom Serializer:

public class RngSerializer : SerializerBase<int>
{
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, int value)
    {
        var rng = new Random().Next(0, 100);
        Console.WriteLine($"Generated rng {rng}");
        context.Writer.WriteInt32(rng);
    }
}

The object:

public class Entity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    
    [BsonSerializer(typeof(RngSerializer))]
    public int RngProp { get; set; }
}

The code that does the inserting:

var entity = new Entity();
collection.InsertOne(entity);
Console.WriteLine($"Inserted Id {entity.Id}, Rng {entity.RngProp}");

You can see that the serializer is called corrected, the value is also set when I check the object in the database. However, the driver doesn't seem to correctly set the property.

Generated rng 32

Inserted Id 5e4ade582c509931f4467e38, Rng 0

I found a solution by triggering the Serializer before the Insert happens like this;

        var bson = entity.ToBson();
        var hydrated = BsonSerializer.Deserialize<Entity>(bson);
        collection.InsertOne(hydrated);
        hydrated.Id = entity.Id;

And changing the Serializer accordingly to;

public class RngSerializer : SerializerBase<int>
{
    #region Overrides of SerializerBase<int>

    public override int Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return context.Reader.ReadInt32();
    }

    #endregion

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, int value)
    {
        //This part is important otherwise it will call the rng twice, once when the ToBson() is called and once when inserting.
        if (value == 0)
        {
            var rng = new Random().Next(0, 100);
            Console.WriteLine($"Generated rng {rng}");
            context.Writer.WriteInt32(rng);
        }
        else
        {
            context.Writer.WriteInt32(value);
        }
    }
}

It might not be the most elegant way with the double serialization, but it gives me the expected results.

UPDATE: pass down the value to the serializer encapsulated in a reference type.

public class MyInt
{
    public int RngProp { get; set; }
}

public class Entity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonSerializer(typeof(RngSerializer))]
    public MyInt MyProp { get; set; } = new MyInt();
}

public class RngSerializer : SerializerBase<MyInt>
{
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, MyInt value)
    {
        var rnd = new Random().Next(0, 100);
        value.RngProp = rnd;
        Console.WriteLine($"written rng {rnd}");
        context.Writer.WriteInt32(rnd);
    }

    public override MyInt Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return new MyInt
        {
            RngProp = context.Reader.ReadInt32()
        };
    }
}


var entity = new Entity();
collection.InsertOne(entity);
Console.WriteLine($"Inserted Id {entity.Id}, Rng {entity.MyProp.RngProp}");

var result = collection.FindSync(e => e.Id == entity.Id).Single();
Console.WriteLine($"Retrieved Id {entity.Id}, Rng {result.MyProp.RngProp}");

Console.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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