public TEntity AddOrUpdate(TKey key, Func <TEntity> addValueFactory, Func <TEntity, TEntity> updateValueFactory) { var result = default(TEntity); _store.AddOrUpdate(GetName(key), s => { result = addValueFactory(); using (var memory = new MemoryStream()) { _strategy.Serialize(result, memory); return(memory.ToArray()); } }, (s2, bytes) => { TEntity entity; using (var memory = new MemoryStream(bytes)) { entity = _strategy.Deserialize <TEntity>(memory); } result = updateValueFactory(entity); using (var memory = new MemoryStream()) { _strategy.Serialize(result, memory); return(memory.ToArray()); } }); return(result); }
public TView AddOrUpdate(TKey key, Func <TView> addValueFactory, Func <TView, TView> updateValueFactory) { var result = default(TView); var filter = GetFilter(key); var query = _collection.Aggregate().Match(filter).As <TView>(); var doc = query.SingleOrDefault(); if (doc == null) { result = addValueFactory(); using (var memory = new MemoryStream()) { _strategy.Serialize(result, memory); var bytes = memory.ToArray(); var json = Encoding.UTF8.GetString(bytes); var bsonDoc = BsonDocument.Parse(json); _collection.InsertOne(bsonDoc); } } else { result = updateValueFactory(doc); using (var memory = new MemoryStream()) { _strategy.Serialize(result, memory); var bytes = memory.ToArray(); var json = Encoding.UTF8.GetString(bytes); var bsonDoc = BsonDocument.Parse(json); _collection.ReplaceOne(filter, bsonDoc); } } return(result); }