TableQuery<T> from Azure TableStorage that filters on PartitionKey

Joey Schluchter picture Joey Schluchter · Nov 20, 2012 · Viewed 17k times · Source

I'm trying to abstract geting all entities from a Table by partitionKey, like so:

public List<T> GetEntities<T>(string partitionKey, T entity) where T : TableEntity
    {
        try
        {
            var tableClient = _account.CreateCloudTableClient();
            var table = tableClient.GetTableReference(entity.GetType().Name.ToLower());
            var exQuery =
                new TableQuery<T>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal,
                                                                             partitionKey));

            var results = table.ExecuteQuery(exQuery).Select(ent => (T) ent).ToList();
            return results;
        }
        catch (StorageException ex)
        {
            //TODO: Add more trace info
            Trace.TraceInformation("Unable to retrieve entity based on query specs");
            return null;
        }
    }

However, It's failing on the

new TableQuery<T>

because the TElement does not have a parameterless constructor.

Answer

Serdar Ozler picture Serdar Ozler · Nov 20, 2012

As you also mentioned in your question, T must have a parameterless constructor. Hence, please change the definition of your method as follows:

public List<T> GetEntities<T>(string partitionKey, T entity) where T : TableEntity, new ()