Home > OS >  Unable to determine the serialization information for
Unable to determine the serialization information for

Time:10-14

While trying to Upsert a list @ MongoDB i get the following error:

"Unable to determine the serialization information for o => o."

Order.cs *(removed properties for testing):

public class Order
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)] 
        public int Id { get; set; }
        public string Number { get; set; }
    }

Upsert:

public async Task SyncAsync(List<Order> orders) 
{

    var bulkUpdateModel = new List<WriteModel<Order>>();

    foreach (var order in orders)
    {
        var filter = Builders<Order>.Filter.Eq(o => o.Id, order.Id);

        var updateDefinition = Builders<Order>.Update.Set(o => o, order);
        var upsertOne = new UpdateOneModel<Order>(filter, updateDefinition) { IsUpsert = true };
        bulkUpdateModel.Add(upsertOne);
    }

    await _orders.BulkWriteAsync(bulkUpdateModel);
}

CodePudding user response:

You could try the ReplaceOneModel instead:

var upsertOne = new ReplaceOneModel<Order>(filter, order)
{
    IsUpsert = true
};

CodePudding user response:

Solution

I found out that you can't update a whole document, only certain properties you set in the updateDefinition...

Not working:

var updateDefinition = Builders<Order>.Update.Set(o => o, order);

Working:

var updateDefinition = Builders<Order>.Update.Set(o => o.Whatever, order.Whatever);

I don't want to use reflection, so switched to Replace where it's possible to update the whole document.

Example

public async Task SyncAsync(List<Order> orders) 
{
    var bulkUpdateModel = new List<WriteModel<Order>>();

    foreach (var order in orders)
    {
        var filter = Builders<Order>.Filter.Eq(o => o, order);
        var writeModel = new ReplaceOneModel<Order>(filter, order) { IsUpsert = true };
        bulkUpdateModel.Add(writeModel);
    }

    await _orders.BulkWriteAsync(bulkUpdateModel);
}
  • Related