Darren Wainwright
Darren Wainwright

Reputation: 30747

Abstracting out queries to the Azure Table Storage using Expressions

I'm creating a class to perform CRUD functionality with Azure Table Storage.

I'm using generic types in this.

I have the following method, which i'm trying to pass in an expression to get used in the TableQuery, but am having some issues.

The line TableQuery<T> query = new TableQuery<T>().Where<T>(criteria); won't compile, and gives me the message

Cannot implicitly convert type 'System.Linq.IQueryable<T>'
to 'Microsoft.WindowsAzure.Storage.Table.TableQuery<T>'. 
An explicit conversion exists (are you missing a cast?)

I understand the message and know it's telling me i'm missing a cast, though I'm unsure how to code it correctly.

My full method is:

 public List<T> GetSome<T>(Expression<Func<T, bool>> criteria) where T : ITableEntity, new()
 {

        TableQuery<T> query = new TableQuery<T>().Where<T>(criteria); // <---- This line isn't working

        List<T> results = table.ExecuteQuery<T>(query).ToList<T>();

        return results;
 }

Upvotes: 3

Views: 2027

Answers (2)

Darren Wainwright
Darren Wainwright

Reputation: 30747

Ok, so I figured it out - how i can pass in a lambda expression for Azure Table Storage to use.

I changed my method to the following:

 public List<T> GetSome<T>(Expression<Func<T, bool>> criteria) where T : ITableEntity, new()
 {                        
    // table, in this case, is my `CloudTable` instance
    List<T> results = table.CreateQuery<T>().Where(criteria).ToList();

    return results;
 }

I can now pass in an expression. For example, to search against a DynamicTableEntity I can use:

 // my table storage class
 TableStorage ts = new TableStorage("ContactData");

 // search with expression
 List<DynamicTableEntity> results = ts.GetSome<DynamicTableEntity>(t => t.Properties["FirstName"].StringValue == "Darren");

If this is something you wouldn't/shouldn't do against an Azure Table Store, please do let me know.

In the meantime, this is how I have met the requirement.

Upvotes: 5

Paul Turner
Paul Turner

Reputation: 39685

The error is because the value returned by the extension method Where is of type IQueryable<T>, but you're assigning to a variable of type TableQuery<T> and there is no implicitly valid type conversion between these types.

Upvotes: 1

Related Questions