Skip to content

Instantly share code, notes, and snippets.

@mahizsas
Forked from gnschenker/MongoDbProjectionWriter.cs
Last active August 29, 2015 14:17
Show Gist options
  • Save mahizsas/60aca3f5a0c73b58e7f3 to your computer and use it in GitHub Desktop.
Save mahizsas/60aca3f5a0c73b58e7f3 to your computer and use it in GitHub Desktop.

Revisions

  1. @gnschenker gnschenker created this gist Jan 17, 2015.
    51 changes: 51 additions & 0 deletions MongoDbProjectionWriter.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    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;
    }
    }
    }