Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 310
Neil Billingham Avatar asked Sep 05 '15 10:09

Neil Billingham


People also ask

How do you create a generic method in C#?

You can create an instance of generic classes by specifying an actual type in angle brackets. The following creates an instance of the generic class DataStore . DataStore<string> store = new DataStore<string>(); Above, we specified the string type in the angle brackets while creating an instance.

What is generic function in C?

Generic functions are functions declared with one or more generic type parameters. They may be methods in a class or struct , or standalone functions. A single generic declaration implicitly declares a family of functions that differ only in the substitution of a different actual type for the generic type parameter.

Can we have generic method in non generic class?

Yes, you can define a generic method in a non-generic class in Java.


1 Answers

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.

like image 80
torvin Avatar answered Nov 14 '22 21:11

torvin