c# - Azure 表存储 - 扩展 ITableEntity 的任何类型的通用下载

标签 c# azure azure-storage azure-table-storage

我有四种自定义数据类型,每种数据类型都扩展ITableEntity,它是WindowsAzure.Storage 包的一部分。

现在,我有四种不同的方法从 Azure 表存储下载数据。每个都遵循以下格式:

public List<MyCustomEntity> DownloadMyCustomEntities(string tableId)
{
    // Reference the CloudTable object
    CloudTable table = tableClient.GetTableReference(tableId);

    TableQuery<MyCustomEntity> query = new TableQuery<MyCustomEntity>();
    return new List<MyCustomEntity>(table.ExecuteQuery(query));
}

我尝试创建一个共享函数,而不是为每种自定义实体类型使用其中一种方法。我希望这是可能的,因为我的所有自定义类型都继承自 ITableEntity

这是我尝试过的:

public List<TableEntity> DownloadAnyEntity(string tableId)
{
    // Reference the CloudTable object
    CloudTable table = tableClient.GetTableReference(tableId);

    TableQuery<TableEntity> query = new TableQuery<TableEntity>();
    return new List<TableEntity>(table.ExecuteQuery(query));
}

我已经用 TableEntityITableEntity 尝试过此操作,但我不断收到错误。对于 TableEntity ,我的错误是不存在对我实际需要的类型的强制转换(当我调用 DownloadAnyEntity 方法时),而我觉得它应该是隐式的,因为它是一个ITableEntity 的扩展。

对于 ITableEntity,我收到一条错误,指出 ExecuteQuery 输入必须是具有公共(public)无参数构造函数的非抽象类型。我的四种自定义类型都有公共(public)无参数构造函数。

我觉得我看到的问题更多地与不完全理解继承有关,更多的是它是 Azure 表存储特定的。非常感谢任何指点。

我基本上一直在关注this documentation ,但没有非特定类型实体下载方法的示例。

最佳答案

您可以使 DownloadAnyEntity 方法变得通用,并对类型参数进行约束

public List<T> DownloadAnyEntity<T>(string tableId) where T: ITableEntity, new()
{
    // Reference the CloudTable object
    var tableRef = tableClient.GetTableReference(tableId);

    var query = new TableQuery<T>();
    return tableRef.ExecuteQuery(query).ToList();
}

然后,可以为从 ITableEntity 继承并具有公共(public)空构造函数的任何类型调用此方法(ExecuteQuery 方法需要一个空构造函数来创建实体)

关于c# - Azure 表存储 - 扩展 ITableEntity 的任何类型的通用下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52695486/

相关文章:

c# - 从车辆图像中提取车牌

c# - 如何设置与单击一次应用程序的文件关联?

azure - 如何从 Web 应用程序使用 Azure 计费 API?

c# - 在 ASP.NET Web API 2 中,ByteRangeStreamContent 在与来自 Azure 存储的流一起使用时返回不正确的数据

azure - Azure 云实例上的共享 Umbraco 媒体文件夹

azure - 将简单控制台应用程序作为 Azure Webjob 运行时出错

c# - 制作 SqlDataAdapter/Datareader "Really Read-Only"

python - Databricks 群集未初始化 Azure 库,错误为 : module 'lib' has no attribute 'SSL_ST_INIT'

python - 在 Python 中使用 SQLAlchemy 连接到 Azure 数据库

c# - ASP MVC 构建对应用程序用户角色导航属性抛出警告?