DB연결

_client = new DocumentClient(new Uri(Config.Instance.CosmosEndPoint), "기본키");
await _client.CreateDatabaseIfNotExistsAsync(new Database { Id = "wjmg_cosmos" });
await _client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(_databaseName), new DocumentCollection
{
    Id = "TESTDATA",
    PartitionKey = new PartitionKeyDefinition
    {
        Paths = new Collection<string> { "/CharactorId" }
    }
});

데이터 정의

public class TestData
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }
 
    public int CharactorId { get; set; }
    public int WeaponId { get; set; }
     
    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}

데이터 가져오기

단일 데이터 가져오기

public async Task<TestData> GetTestData(long uid, int CharatorId)
{
    try
    {
        var readDocument = await _client.ReadDocumentAsync<TestData>(UriFactory.CreateDocumentUri(_databaseName, "TESTDATA", $"{uid}"), new RequestOptions()
        {
            PartitionKey = new PartitionKey(CharatorId)
        });
 
        return readDocument;
    }
    catch (DocumentClientException de)
    {
        if (de.StatusCode == HttpStatusCode.NotFound)
        {
            return null;
        }
        else
        {
            LogSystem.Instance.RegistLog($"Error: {de.Message}, Message: {de.Message}", SYSTEM_LOG_LEVEL.CRITICAL);
 
        }
    }
    catch (Exception e)
    {
        var baseException = e.GetBaseException();
        LogSystem.Instance.RegistLog($"Error: {e.Message}, Message: {baseException.Message}",
            SYSTEM_LOG_LEVEL.CRITICAL);
    }
 
    return null;
}

쿼리하여 가져오기

public bool GetTestDatas(int charatorId, out List<TestData> results)
{
    try
    {
        var collectionLink = UriFactory.CreateDocumentCollectionUri(_databaseName, "TESTDATA");
 
        var query = new SqlQuerySpec(
            "SELECT TOP 10 * FROM TESTDATA c WHERE c.CharatorId = @charatorIndex ORDER BY c._ts DESC",
            new SqlParameterCollection(new[] { new SqlParameter { Name = "@charatorIndex", Value = charatorId } }));
 
        results = _client.CreateDocumentQuery<TestData>(collectionLink, query)
            //.Where(p => p.CharatorId == charatorId)
            .ToList();
        return true;
    }
    catch (DocumentClientException de)
    {
        results = null;
        return de.StatusCode == HttpStatusCode.NotFound;
    }
    catch (Exception e)
    {
        var baseException = e.GetBaseException();
        LogSystem.Instance.RegistLog($"Error: {e.Message}, Message: {baseException.Message}",
            SYSTEM_LOG_LEVEL.CRITICAL);
    }
    results = null;
    return false;
}

데이터 저장하기