我正在用头撞墙。
我有一个基本上是 Upsert 的函数,名为 TryCreateOrUpdate
.我确实意识到现在存在一个 upsert 函数,但这是一些较旧的代码。这是函数:
public static async Task<string> TryCreateOrUpdate<T>(T data) where T : ViewModelBase
{
var options = string.IsNullOrWhiteSpace(data.PartitionKey) ? null : new RequestOptions { PartitionKey = new PartitionKey(data.PartitionKey) };
try
{
var response = await Client.CreateDocumentAsync(Collection.SelfLink, data, options, true);
}
catch (DocumentClientException dce)
{
switch (dce.StatusCode.Value)
{
...
case HttpStatusCode.Conflict:
try
{
var link = UriFactory.CreateDocumentUri(_databaseId, _collectionId, data.Id);
await Client.ReplaceDocumentAsync(link, item, options);
}
catch (Exception e)
{
return $"There was an error updating the document.";
}
break;
default:
...
}
}
catch (Exception e)
{
return "There was an unknown error creating the document.";
}
return "OK";
}
我正在尝试插入一个 id 为 6 位数的文档作为字符串。
我检查了我的 Cosmos DB,我可以确认数据库中没有我试图更新的 ID 的文档。所以它应该导致创建。
创建文档的行抛出
DocumentClientException
:Entity with the specified id already exists in the system.
但是,替换代码行会引发此异常:
Entity with the specified id does not exist in the system.
嗯什么?到底存在不存在?!
正如我所说,我在运行之前进行了检查,并且该文档不存在。
我什至尝试更改所有这些代码以使用较新的
UpsertDocumentAsync
我仍然收到错误Entity with id already exists in the system
尽管如此,正如我所说,该文件不存在。
最佳答案
虽然我不太了解与此问题相关的 CosmosDb 和相关包的内部工作原理,但似乎原因是重写了基类中的 Id 字段的编写方式。
以前是这样写的:
public string id => Id;
public string Id { get; set; }
然后它变成了:
[JsonProperty("id")]
public string Id { get; set; }
请注意, id => Id 已被删除。现在它引起了问题。我们将其更改为:
public string id {
get { return Id; }
set { Id = value; }
}
public string Id { get; set; }
现在一切都像以前一样。
关于c# - 具有 id 的实体已存在且在 CosmosDB 中不同时存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57385244/