How can I Build a Generic Method in c# to Query a Partition in a Given Azure Table

ぃ、小莉子 提交于 2021-02-07 13:52:12

问题


I'm trying to build a generic method to return entries in a partition in a given Azure table. This is how it looks:

public class Table : ITable
    {
        private CloudStorageAccount storageAccount;
        public Table()
        {
            var storageAccountSettings = ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ToString();
            storageAccount = CloudStorageAccount.Parse(storageAccountSettings);
        }

        public async Task<IEnumerable<T>> RetrieveAllInPartition<T>(string tableReference, string partitionKey) where T : ITableEntity
        {
            var tableClient = storageAccount.CreateCloudTableClient();
            var table = tableClient.GetTableReference(tableReference);
            var query = new TableQuery<T>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey));
            var results = await table.ExecuteQuerySegmentedAsync<T>(query,null);
            return results;
        }
    }

This doesn't compile I get:

CS0310 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TElement' in the generic type or method
'CloudTable.ExecuteQuerySegmentedAsync(TableQuery, TableContinuationToken)'

Any ideas how I can resolve this?


回答1:


You need to add new() constraint to your generic parameter:

public async Task<IEnumerable<T>> RetrieveAllInPartition<T>(string tableReference, string partitionKey) 
    where T : ITableEntity, new()

since ExecuteQuerySegmentedAsync also has this constraint (as can be seen in the documentation).

This constraint is required by ExecuteQuerySegmentedAsync because otherwise it won't be able to create instances of T for you. Please refer to the documentation to read more about the new() constraint.



来源:https://stackoverflow.com/questions/32411926/how-can-i-build-a-generic-method-in-c-sharp-to-query-a-partition-in-a-given-azur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!