Космос Вставка работает только один раз - PullRequest
0 голосов
/ 08 февраля 2020

Я надеюсь, что кто-то может помочь мне с этой проблемой. У меня есть два метода, которые вставляют документ в БД Cosmos. Один работает каждый раз, когда я запускаю его. Другой доходит до CreateDatabaseIfNotExistsAsyn c, выходит из метода и возвращается к вызывающему методу. Свойство Status объектов ItemReponse говорит: «WaitingForActivation».

Я скажу, что эта логика c сработала один раз, а теперь (без изменений) - нет. Ниже код, который умирает. Сначала юнит-тест:

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");
}

Позвольте мне добавить, что я использую Эмулятор Космоса, следовательно, url localhost. Теперь код, который умирает.

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 Ответ

1 голос
/ 08 февраля 2020

Вы смешиваете syn c и asyn c в своем коде здесь.

Используйте await в этой строке.

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

, а также эта вызывающая функция должна быть также асин c

public void AddPerson()
...