Forked from gnschenker/MongoDbProjectionWriter.cs
Last active
August 29, 2015 14:17
-
-
Save mahizsas/60aca3f5a0c73b58e7f3 to your computer and use it in GitHub Desktop.
MongoDb Projection Writer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using MongoDB.Bson; | |
using MongoDB.Driver; | |
using MongoDB.Driver.Builders; | |
namespace Recipes.ReadModel | |
{ | |
public class MongoDbProjectionWriter<T> : IProjectionWriter<T> | |
where T: class | |
{ | |
private const string DATABASE_NAME = "Recipes"; | |
private readonly string connectionString; | |
private static MongoCollection<T> _collection; | |
public MongoDbProjectionWriter(string connectionString) | |
{ | |
this.connectionString = connectionString; | |
} | |
public void Add(int id, T item) | |
{ | |
var collection = GetCollection(); | |
collection.Insert(item); | |
} | |
public void Update(int id, Action<T> update) | |
{ | |
var query = Query.EQ("_id", new BsonInt32(id)); | |
var collection = GetCollection(); | |
var existingItem = collection.FindOneAs<T>(query); | |
if (existingItem == null) | |
throw new InvalidOperationException("Item does not exists"); | |
update(existingItem); | |
collection.Save(existingItem); | |
} | |
private MongoCollection<T> GetCollection() | |
{ | |
if (_collection == null) | |
{ | |
var client = new MongoClient(connectionString); | |
var server = client.GetServer(); | |
var database = server.GetDatabase(DATABASE_NAME); | |
_collection = database.GetCollection<T>(typeof(T).Name); | |
} | |
return _collection; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment