Azure表存储对象的通用查询

时间:2019-02-06 06:48:16

标签: c# azure generics azure-table-storage

我正在尝试通过Crud操作创建对Azure表存储的常规访问,但是遇到了一个问题,即我的服务似乎必须依赖属性名才能查询单个记录。

我的通用服务

public class AzureTableStorageService<T> where T : CustomTableEntity, new()
{
    private readonly CloudStorageAccount _storageAccount;
    private readonly CloudTableClient _tableClient;

    public AzureTableStorageService()
    {
        _storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
        _tableClient = _storageAccount.CreateCloudTableClient();
    }

    // How do I make this generic if I know all objects 
    // calling this have a single primary key Id field?
    public GameEntity GetGameEntityById(string tableName, int id)
    {
        var table = GetStorageTable(tableName);

        // I want to swap GameEntity for T here but then I lose 
        // the understanding that it has an Id field to Query by
        IEnumerable<GameEntity> query = (from game in table.CreateQuery<GameEntity>()
                                         where game.Id == id
                                         select game);

        return query.FirstOrDefault();
    }

    // I am successfully inserting generically here
    public void InsertRequestToStorage(Guid operationId, ITableEntity entity, string tableName)
    {
        TableOperation insertOperation = TableOperation.Insert(entity);
        CloudTable table = GetStorageTable(tableName);

        table.Execute(insertOperation);
    }

    // I am successfully getting all entities on a table generically here 
    public List<T> GetTableEntities(string tableName)
    {
        CloudTable table = GetStorageTable(tableName);

        TableContinuationToken token = null;
        var entities = new List<T>();
        do
        {
            var queryResult = table.ExecuteQuerySegmented(new TableQuery<T>(), token);
            entities.AddRange(queryResult.Results);
            token = queryResult.ContinuationToken;
        } while (token != null);

        return entities;
    }
}

如果我知道以这种方式访问​​的所有表都应具有带有ID的单个主键,是否可以动态访问该表中的单个记录?

0 个答案:

没有答案