Created
January 17, 2015 23:53
-
-
Save gnschenker/f013ac20287c4b7c1c52 to your computer and use it in GitHub Desktop.
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