简体   繁体   English

使用.NET反射查询Azure表存储

[英]Querying Azure table storage using .NET reflection

I want to write a function GetAny() that can query and return a row from any table in the Azure Table Storage just by supplying the table name tableName and the entity type T with LINQ. 我想编写一个函数GetAny() ,只需提供表名tableName和带有LINQ的实体类型T ,就可以查询和返回Azure表存储中任何表的行。 So far what I've tried is as follows: 到目前为止,我尝试过的方法如下:

public T GetAny<T>(TableServiceContext tableStorageServiceContext, 
    string tableName, string partitionKey, string applicationName)
{
    var results = from c in tableStorageServiceContext.CreateQuery<T>(tableName)
        where ((T)c).PartitionKey == partitionKey
        select c;

    var query = results.AsTableServiceQuery();
    return query.Execute().FirstOrDefault();
}

, which does not compile since I'm not allowed to cast c into T like I'm trying to. ,它无法编译,因为不允许像我想的那样将c转换为T

I also tried to default to TableServiceEntity , but then I still have to cast the resulting TableServiceEntity into the true entity type after GetAny() has been invoked: 我也尝试默认使用TableServiceEntity ,但是在调用GetAny()之后,我仍然必须将结果TableServiceEntity转换为真实的实体类型:

TableServiceEntity GetAny(string tableName, string partitionKey)
{
    var results = from c in _tableStorageServiceContext.CreateQuery<TableServiceEntity>(tableName)
                  where c.PartitionKey == partitionKey 
                  select c;

    var query = results.AsTableServiceQuery();
    return query.Execute().FirstOrDefault();
}

Is there a way of doing this with .NET reflection, or perhaps there are other ways of querying the Azure Table Storage that supports not having to implicitly specify the entity type? 是否可以通过.NET反射做到这一点,或者还有其他查询Azure表存储的方法,这些方法支持不必隐式指定实体类型?

You can use following code to query from any Storage Table: 您可以使用以下代码从任何存储表中查询:

/// <summary>
/// Returns table entities
/// </summary>
public List<dynamic> GetEntities(string tableName, int takeCount, string filters)
    {

        var table = TableClient.GetTableReference(tableName);

        var tableQuery = !filters.IsEmpty()
                             ? new TableQuery<DynamicTableEntity>().Where(filters).Take(takeCount)
                             : new TableQuery<DynamicTableEntity>().Take(takeCount);

        var tableResult = table.ExecuteQuery(tableQuery);

        List<dynamic> dynamicCollection = tableResult.ToDynamicList();

        return dynamicCollection;
    }

The extension method ToDynamicList basically reads through each entity on the result and maps the property value as dynamic type. 扩展方法ToDynamicList基本上读取结果上的每个实体,并将属性值映射为dynamic类型。 Storage Library by default hides the values behind bunch of properties such as .BinaryValue , 'BoolValue' 默认情况下,存储库将值隐藏在诸如.BinaryValue ,'BoolValue'等一系列属性的后面

I wrote a generic Storage Table Browser which you can find on github 我写了一个通用的存储表浏览器,您可以在github上找到它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM