波斯菊插入仅工作一次

时间:2020-02-07 23:42:25

标签: c# .net-core azure-cosmosdb webapi

我希望有人可以帮助我解决这个问题。我有两种将文档插入Cosmos DB的方法。每当我运行它时,它都会起作用。另一个到达CreateDatabaseIfNotExistsAsync并退出该方法并返回到调用方法。 ItemReponse对象的Status属性显示为“ WaitingForActivation”。

我要说的是,这种逻辑确实曾经起作用过(现在没有任何变化),但是没有起作用。下面是死亡的代码。首先进行单元测试:

public void AddPerson()
{
    var logger = Mock.Of<ILogger<Person>>();
    var appset = Mock.Of<IAppSettings>();

    appset.DatabaseName = "PersonsDB";
    appset.ContainerName = "PersonsContainer";
    appset.EndpointUrl = "https://localhost:8081";
    appset.AuthorizationKey = "somesecretkey";

    Person person = new Person()
    {
        id = Guid.NewGuid().ToString(),
        Address_line_1 = "1932 Alakea St",
        Address_line_2 = "",
        Birth_Date = "2020-01-01",
        Gender = "m",
        Patient_First_Name = "John",
        Patient_Last_Name = "Ridley",
        Hospital_Code = "Queens Med",
        Rec_ID = "1111111111",
        VER_CRM_ID = "22222222",
        VER_EMAIL = "JR@noemail.com",
    };

    PersonCosmos personCosmos = new PersonCosmos(logger, appset);
    var myresult = personCosmos.PutPersonData(person);
    Assert.True(myresult.Exception == null, "Row added");
}

让我补充一下,我正在运行Cosmos Emulator,因此正在运行localhost URL。现在该死的代码了。

public async Task<ItemResponse<Person>> PutPersonData(Person persondata)
{
    this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
    this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(DatabaseName);
    this.container = await this.database.CreateContainerIfNotExistsAsync(ContainerName, "/Hospital_Code");
    ItemResponse<Person> PutResponse = null;

    try
    {
        // Read the item to see if it exists.  
        PutResponse = await this.container.ReadItemAsync<Person>(persondata.id.ToString(), new PartitionKey(persondata.Hospital_Code ));
        return PutResponse;
    }
    catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
    {
        // Create an item in the container representing the Appointment. Note we provide the value of the partition key for this item, which is "Hospital_Code"
        PutResponse = await this.container.CreateItemAsync<Person>(persondata, new PartitionKey(persondata.Hospital_Code));
        return PutResponse;
    }
    catch (Exception ex)
    {
        // Create an item in the container representing the object. Note we provide the value of the partition key for this item, which is "Hospital_Code"
        _logger.LogError($"Error in {0} at {1} " + ex.Message, System.Reflection.MethodBase.GetCurrentMethod().Name, DateTime.UtcNow.ToLongTimeString());
        return PutResponse;
    }
}

1 个答案:

答案 0 :(得分:1)

您正在此处在代码中混合同步和异步。

在此行上使用await。

var myresult = **await** personCosmos.PutPersonData(person); 

并且此调用函数也应该异步

public void AddPerson()