![](/img/trans.png)
[英]Why do I get the error, “Object reference not set to an instance of an object”?
[英]Why do I get the "reference not set to an instance of an object?
我正在使用新的 CosmosDB SDK v3 https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-sdk-dotnet-standard和一個非常簡單的插入,我已經驗證了所有對象確實不為空並且具有合理的值,但我仍然收到錯誤消息:
[1/12/2019 10:35:04] System.Private.CoreLib: Exception while executing function: HAPI_HM_Seasons. Microsoft.Azure.Cosmos.Direct: Object reference not set to an instance of an object.
我不明白為什么這是我必須在這里遺漏一些非常基本的東西,但我不能指望它。
代碼如下:
List<SeasonInformation> seasonInformationList = new List<SeasonInformation>();
foreach(JObject document in listOfSeasons)
{
SeasonInformation seasonInformation = new SeasonInformation
{
id = Guid.NewGuid().ToString(),
Brand = brand,
IntegrationSource = source,
DocumentType = Enums.DocumentType.Season,
UpdatedBy = "HAPI_HM_Seasons",
UpdatedDate = DateTime.Now.ToString(),
UpdatedDateUtc = string.Format("{0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow),
OriginalData = document
};
seasonInformationList.Add(seasonInformation);
}
database = cosmosClient.GetDatabase(cosmosDBName);
container = database.GetContainer(cosmosDBCollectionNameRawData);
log.LogInformation(string.Format("HAPI_HM_Seasons BASIC setup done at {0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow));
log.LogInformation(string.Format("HAPI_HM_Seasons import {1} items BEGIN at {0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow, seasonInformationList.Count));
foreach(var season in seasonInformationList)
{
ItemResponse<SeasonInformation> response = await container.CreateItemAsync(season);
}
我已經驗證列表已填充並且循環中的季節變量包含正確的數據,所以我在這里有點卡住了。
異常發生在我嘗試CreateItemAsync
到 CosmosDB 的最后一個 foreach 循環中
作為最佳實踐,您需要在所有 Cosmosdb 方法中使用帶有 await 的 Async 方法,以確保它們被執行並獲得響應,
並按如下方式修改您的 CreateItemAsync,
ItemResponse<SeasonInformation> response = await container.CreateItemAsync(season, new PartitionKey(season.whatever));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.