Last active
August 29, 2015 14:05
-
-
Save davidwhitney/7f88e26ea13fcdc38040 to your computer and use it in GitHub Desktop.
DocumentDb repo for Azure DocumentDb
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
public class DocumentDbStore : IStorage | |
{ | |
private string endpoint = "rootUri"; | |
private string authKey = "key"; | |
private readonly DocumentClient _client; | |
private readonly DocumentCollection _col; | |
public DocumentDbStore() | |
{ | |
_client = new DocumentClient(new Uri(endpoint), authKey); | |
var databases = _client.CreateDatabaseQuery().Where(x => x.Id == "DbName").ToList(); | |
var database = databases.Any() ? databases.First() : _client.CreateDatabaseAsync(new Database {Id = "DbName"}).Result; | |
var collections = _client.CreateDocumentCollectionQuery(database.SelfLink) | |
.Where(x => x.Id == "CollectionName").ToArray(); | |
_col = collections.Any() | |
? collections.First() | |
: _client.CreateDocumentCollectionAsync(database.SelfLink, | |
new DocumentCollection {Id = "CollectionName"}).Result; | |
} | |
public void Store<TObjectType>(TObjectType obj) where TObjectType : class, IPersistable | |
{ | |
var existing = | |
_client.CreateDocumentQuery(_wishlists.SelfLink, | |
"SELECT * FROM CollectionName c WHERE c.Id = '" + obj.Id + "'").ToList(); | |
if (existing.Any()) // This is REALLY POOR - but I'm not sure how to replace a TObjectType yet.. | |
{ | |
var first = existing.First(); | |
var selfLinkForUpdate = (string) first._self.ToString(); | |
var deleteResult = _client.DeleteDocumentAsync(selfLinkForUpdate).Result; | |
} | |
var resp = _client.CreateDocumentAsync(_wishlists.SelfLink, obj).Result; | |
} | |
public TObjectType Get<TObjectType>(string id) where TObjectType : class, IPersistable | |
{ | |
var list = _client.CreateDocumentQuery<TObjectType>(_col.SelfLink) | |
.Where(d => d.WishlistId == id).ToList(); | |
return list.FirstOrDefault() as TObjectType; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment