我刚刚开始使用DocumentDB,我创建了一个新的Repository
类来管理文档(我使用的是DocumentDB Emulator)。当我尝试添加文档时,我收到此错误:
An unhandled exception of type 'System.NullReferenceException' occurred in mscorlib.dll
修改
每个变量都设置正确。我认为它与我从WebAPI异步调用它的方式有关。需要帮助。
我的Repository
课程如下:
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);
}
}
在Global.asax
中,我初始化数据库Application_Start()
// Initialize DocumentDB.
DocumentDB.Repository<DataCache.DocumentDB.Models.Post>.Initialize();
我在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);
}
解
我已经改变了我在WebAPI中调用方法的方式,并且它可以工作:
[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);
}
哦,是的,一个fr d !! ...