0

I've just started to use DocumentDB and I have created a new Repository class to manage documents (I use DocumentDB Emulator). When I try to add a document I get this error:

An unhandled exception of type 'System.NullReferenceException' occurred in mscorlib.dll

EDIT

Every variables are set correctly. I think it as something to do with the way I call it asynchronously from WebAPI. Need help on this one.

My Repository class looks like that:

public static class Repository<T> where T : class
{
    private static readonly string Database = ConfigurationManager.AppSettings["DocumentDBDatabase"];
    private static DocumentClient Client;

    public static void Initialize()
    {
        Client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["DocumentDBEndpoint"]), ConfigurationManager.AppSettings["DocumentDBAuthKey"], new ConnectionPolicy { EnableEndpointDiscovery = false });

        IsDatabaseExists().Wait();                        
    }

    private static async Task IsDatabaseExists()
    {
        Database database = Client.CreateDatabaseQuery()
                                .Where(db => db.Id == Database)
                                .AsEnumerable()
                                .FirstOrDefault();

        if (database == null)
        {
            database = await Client.CreateDatabaseAsync(new Database { Id = Database });

            // Create collections.
            DocumentCollection post = await Client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = "Post" });                
        }
    }

    public static async Task<Document> CreateItem<T>(T item)
    {
        return await Client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(Database, "Post"), item);
    }
}

In Global.asax, I initialize the Database Application_Start()

// Initialize DocumentDB.            
DocumentDB.Repository<DataCache.DocumentDB.Models.Post>.Initialize();

I add document in a WebAPI:

[Route("api/data-cache/posts")]
[HttpPost]
public HttpResponseMessage AddPosts([FromBody] DataCache.DocumentDB.Models.Post post)
{
    DataCache.DocumentDB.Repository<DataCache.DocumentDB.Models.Post>.CreateItem(post);

    return Request.CreateResponse(HttpStatusCode.OK);
}

SOLUTION

I've changed the way I call the method in the WebAPI and it work:

[Route("api/data-cache/posts")]
[HttpPost]
public async Task<HttpResponseMessage> AddPosts([FromBody] DataCache.DocumentDB.Models.Post post)
{
    await DataCache.DocumentDB.Repository<DataCache.DocumentDB.Models.Post>.CreateItem(post);

    return Request.CreateResponse(HttpStatusCode.OK);
}

Oh yeah, a frigging dulicate!!!

Jonathan Anctil
  • 1,025
  • 3
  • 20
  • 44

0 Answers0