Skip to content

Instantly share code, notes, and snippets.

@davidwhitney
Created March 14, 2011 22:53
Show Gist options
  • Save davidwhitney/870037 to your computer and use it in GitHub Desktop.
Save davidwhitney/870037 to your computer and use it in GitHub Desktop.
CouchDb quickstart example
using System;
using System.Web.Mvc;
using Divan;
using Newtonsoft.Json;
namespace CouchTest.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
const string host = "localhost";
const int port = 5984;
var server = new CouchServer(host, port);
var db = server.GetDatabase("myfirstdatabase");
var document = new SomeRandomAggregateRoot
{This = "Is cool!", Subclass = new SomeRandomClass {IsAwesome = "hell yeah!"}};
using (var couchRepo = new CouchRepository<SomeRandomAggregateRoot>(db))
{
var id = couchRepo.Save(document);
var returnedCouchDoc = couchRepo.Retrieve(id);
ViewData["Message"] = returnedCouchDoc._id;
}
return View();
}
public ActionResult About()
{
return View();
}
}
public class CouchRepository<T> : CouchRepository where T : CouchAggregateRoot
{
public CouchRepository(ICouchDatabase couchDatabase):base(couchDatabase)
{
}
public T Retrieve(string id)
{
return Retrieve<T>(id);
}
public string Save(T @object)
{
return Save<T>(@object);
}
}
public class CouchRepository: IDisposable
{
protected readonly ICouchDatabase CouchDatabase;
public CouchRepository(ICouchDatabase couchDatabase)
{
CouchDatabase = couchDatabase;
}
public string Save<T>(T @object) where T : CouchAggregateRoot
{
var couchDocument = new CouchDocumentWrapper<T>(@object);
CouchDatabase.SaveDocument(couchDocument);
return couchDocument.Id;
}
public T Retrieve<T>(string id) where T : CouchAggregateRoot
{
var rawDocument = CouchDatabase.GetDocument(id);
var @object = JsonConvert.DeserializeObject<T>(rawDocument.ToString());
@object._id = rawDocument.Id;
@object._rev = rawDocument.Rev;
return @object;
}
public void Dispose()
{
// Should probably get round to implementing this...
}
}
public class CouchAggregateRoot : ICouchAggregateRoot
{
public string _id { get; set; }
public string _rev { get; set; }
}
public interface ICouchAggregateRoot
{
string _id { get; set; }
string _rev { get; set; }
}
public class SomeRandomAggregateRoot : CouchAggregateRoot
{
public string This { get; set; }
public SomeRandomClass Subclass { get; set; }
}
public class SomeRandomClass
{
public string IsAwesome { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment