6
votes

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 edited your code and now the error message you provided and my answer doesn't make sense :)torvin
@tovin, apologies; your answer is correct (expect that the new() constraint had to be the last constraint in the statement - which I edited before upvoting/checking) - also I realised that ExecuteQuery has no async method available so had to go with ExecuteQuerySegmentedAsync - I'll edit references to ExecuteQuery in your answer too if that's ok with you? :)Neil Billingham
sure :) don't forget to edit your error message as welltorvin

1 Answers

24
votes

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.