Search code examples
c#azureazure-storageazure-table-storage

Azure Table Storage - Query Where return other data


I'm not sure why, but I'm querying database with predicate City = London but I'm receiving entities with different values

Here's my data model:

public class MyEntity : TableEntity
{

    public MyEntity()
    {
    }

    public MyEntity(string partitionKey, string rowKey) : base(partitionKey, rowKey)
    {
    }

    public string City { get; set; }

    public string Year { get; set; }
}

My query:

var query = new TableQuery<KomisEntity>()
            .Where(TableQuery.GenerateFilterCondition("City", QueryComparisons.Equal, "London"))
            .Where(TableQuery.GenerateFilterCondition("Year", QueryComparisons.Equal, "2000"));

var data = await LoadWhereAsync(table, query);

Helper method:

private static async Task<List<T>> LoadWhereAsync<T>(CloudTable table, TableQuery<T> query) where T : TableEntity, new()
{
    var entities = new List<T>();


    TableContinuationToken continuationToken = null;
    do
    {
        var page = await table.ExecuteQuerySegmentedAsync(query, continuationToken);
        continuationToken = page.ContinuationToken;
        entities.AddRange(page);
    }
    while (continuationToken != null);

    return entities;
}

But for some reason I'm receiving entities e.g with:

City: 'South Pierceberg'

Thanks in advance


Solution

  • The issue is due to your query filter:

    var query = new TableQuery<KomisEntity>()
                .Where(TableQuery.GenerateFilterCondition("City", QueryComparisons.Equal, "London"))
                .Where(TableQuery.GenerateFilterCondition("Year", QueryComparisons.Equal, "2000"));
    

    This should generate an or filter like this city==London or Year==2000.

    You can try the code below, which uses and filter:

    string filter = "(City eq 'London') and (Year eq '2000')";
    var query = new TableQuery<KomisEntity>().Where(filter);
    

    or use this query format:

    var query = new TableQuery<KomisEntity>().Where(
                            TableQuery.CombineFilters(
                                TableQuery.GenerateFilterCondition("City", QueryComparisons.Equal, "London"),
                                TableOperators.And,
                                TableQuery.GenerateFilterCondition("Year", QueryComparisons.Equal, "2000")
                                )
                        );