使用nuget包“ Microsoft.Azure.Cosmos”(版本3.4.1)我无法在非常基本的模型(三个属性)上执行upsert操作。我已经查看了宇宙样本,并以它们为起点,但无法弄清楚我在做什么错
当尝试执行以下代码时,出现以下错误 “指定的输入之一无效” 。
完整代码
public class CatalogModel
{
[JsonProperty("id")]
public long Id { get { return ModelId; } }
[JsonProperty("ModelId")]
public long ModelId { get; set; }
public string Name { get; set; }
}
public async Task Do(CatalogModel model)
{
string databaseId = "<dbid_here>"; // in real application this will not be hard coded
string containerId = "<containerid_here>"; // in real application this will not be hard coded
Database database = await _client.CreateDatabaseIfNotExistsAsync(databaseId);
// Delete the existing container to prevent create item conflicts
using (await database.GetContainer(containerId).DeleteContainerStreamAsync())
{ }
// We create a partitioned collection here which needs a partition key. Partitioned collections
// can be created with very high values of provisioned throughput (up to Throughput = 250,000)
// and used to store up to 250 GB of data. You can also skip specifying a partition key to create
// single partition collections that store up to 10 GB of data.
ContainerProperties containerProperties = new ContainerProperties(containerId, partitionKeyPath: "/ModelId");
// Create with a throughput of 1000 RU/s
Container _container = await database.CreateContainerIfNotExistsAsync(
containerProperties,
throughput: 1000);
try
{
var id = model.ModelId.ToString();
var partitionKey = new PartitionKey(id);
var response = await _container.ReadItemStreamAsync(
id: id,
partitionKey: partitionKey,
cancellationToken: context.CancellationToken);
ItemResponse<CatalogModel> itemResponse;
if (response.IsSuccessStatusCode)
{
//TODO: implement
}
else
{
var item = model
// This is not working either
//itemResponse = await _container.UpsertItemAsync<CatalogModel>(
// item,
// partitionKey: partitionKey,
// cancellationToken: context.CancellationToken);
using (Stream stream = ToStream<CatalogModel>(item))
{
string body;
using (var reader = new StreamReader(stream, new UTF8Encoding(false, true), false, 1024, true))
{
body = await reader.ReadToEndAsync();
}
stream.Seek(0, SeekOrigin.Begin);
using (ResponseMessage responseMessage = await _container.UpsertItemStreamAsync(
partitionKey: partitionKey,
streamPayload: stream))
{
using (var reader = new StreamReader(responseMessage.Content, new UTF8Encoding(false, true), false, 1024, true))
{
body = await reader.ReadToEndAsync();
}
}
}
}
}
catch (Exception ex)
{
throw;
}
答案 0 :(得分:1)
id
必须是string
。您的模型可能需要为:
public class CatalogModel
{
[JsonProperty("id")]
public string Id { get { return ModelId.ToString(); } }
[JsonProperty("ModelId")]
public long ModelId { get; set; }
public string Name { get; set; }
}
答案 1 :(得分:1)