-
Notifications
You must be signed in to change notification settings - Fork 0
/
TableStoreRepository.cs
88 lines (74 loc) · 3.12 KB
/
TableStoreRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using Microsoft.Azure.Cosmos.Table;
namespace dnkh.TableStoreRepository;
public class TableStoreRepository<T> : IRepository<T>
{
private CloudTable? _cloudTable = null;
private readonly TableStoreConfiguration _config;
public TableStoreRepository(TableStoreConfiguration configuration)
{
_config = configuration;
}
private async Task<CloudTable> GetCloudTable()
{
if (_cloudTable is null)
{
CloudTableClient tableClient = new(new Uri(_config.StorageUri),
new StorageCredentials(_config.SASToken));
_cloudTable = tableClient.GetTableReference(_config.TableName);
await _cloudTable.CreateIfNotExistsAsync();
}
return _cloudTable;
}
public virtual async Task<IEnumerable<T>?> GetAsync(int? skip = 0, int? take = 100)
{
var cloudTable = await GetCloudTable();
var query = new TableQuery<TableEntityAdapter<T>>();
int localTake = take ?? 100;
int localSkip = skip ?? 0;
query.TakeCount = localTake >= 1000 ? 1000 : localTake;
var result = new List<TableEntityAdapter<T>>();
TableContinuationToken token = null;
do
{
var queryResult = await cloudTable.ExecuteQuerySegmentedAsync<TableEntityAdapter<T>>(query, token);
result.AddRange(queryResult.Results);
token = queryResult.ContinuationToken;
} while (token != null);
return result.Select(x => x.OriginalEntity).Skip(localSkip).Take(localTake);
}
public virtual async Task<T?> GetByGuidAsync(Guid id)
{
var cloudTable = await GetCloudTable();
var queryResult = cloudTable.ExecuteQuery(new TableQuery<TableEntityAdapter<T>>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, id.ToString())));
return queryResult.Select(x => x.OriginalEntity).FirstOrDefault();
}
public virtual async Task<T?> UpsertAsync(T entity, string? rowKey = null, string? partitionKey = null)
{
var cloudTable = await GetCloudTable();
var tableEntity = new TableEntityAdapter<T>(entity);
if (partitionKey is null)
{
partitionKey = _config.PartitionKey;
}
if (rowKey is null)
{
rowKey = Guid.NewGuid().ToString();
}
tableEntity.PartitionKey = partitionKey;
tableEntity.RowKey = rowKey;
await cloudTable.ExecuteAsync(TableOperation.InsertOrReplace(tableEntity));
return entity;
}
public virtual async Task<T?> DeleteAsync(Guid id)
{
var cloudTable = await GetCloudTable();
var queryResult = cloudTable.ExecuteQuery(new TableQuery<TableEntityAdapter<T>>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, id.ToString())));
var entity = queryResult.FirstOrDefault();
if (entity is null)
{
return default(T?);
}
await cloudTable.ExecuteAsync(TableOperation.Delete(entity));
return entity.OriginalEntity;
}
}