2014-05-23 44 views
2

我正在创建一个类来使用Azure表存储执行CRUD功能。使用表达式抽取对Azure表存储的查询

我在这里使用泛型类型。

我有下面的方法,我试图通过一个表达式来使用TableQuery,但我有一些问题。

线TableQuery<T> query = new TableQuery<T>().Where<T>(criteria);将无法​​编译,并给我的消息

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

我明白了消息,并知道它告诉我,我缺少强制,但我不能确定如何将其正确编码。

我满的方法是:

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; 
} 

回答

2

好的,所以我想通了 - 我如何传递一个lambda表达式来使用Azure表存储。

我改变方法为以下:

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; 
} 

我现在可以通过在表达。例如,要搜索针对DynamicTableEntity,我可以使用:

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

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

如果这是你不会/不应该做针对Azure的表店,请不要让我知道。

与此同时,这是我满足要求的方式。

1

的错误是因为扩展方法Where返回的值是IQueryable<T>型的,但你分配给TableQuery<T>类型的变量并没有隐含有效这些类型之间的类型转换。

+1

我明白这一点。我挣扎的地方是我如何才能让它工作。我想我正在使用错误的方法,但不知道我应该使用哪一个来传递lambda。 – Darren