简体   繁体   中英

How can I parameterise Azure's TableOperation.Retrieve<TElement> in a method in c# .NET

I have a class, something like the following:

public class Table : ITable
    {
        private CloudStorageAccount storageAccount;
        public Table()
        {
            var storageAccountSettings = ConfigurationManager.ConnectionStrings["AzureStorageConnection"].ToString();
            storageAccount = CloudStorageAccount.Parse(storageAccountSettings);
        }
        public async Task<TableResult> Retrieve(string tableReference, string partitionKey, string rowKey)
        {
            var tableClient = storageAccount.CreateCloudTableClient();
            var table = tableClient.GetTableReference(tableReference);
            TableOperation retrieveOperation = TableOperation.Retrieve<SomeDomainModelType>(partitionKey, rowKey);
            TableResult retrievedResult = await table.ExecuteAsync(retrieveOperation);
            return retrievedResult;
        }
    }

This class is a wrapper to retrieve a single entity from an Azure table. It's wrapped up and conforms to an interface so that it can be stubbed out with Microsoft Fakes during testing. It works at the moment, however it would be more elegant if the following was more generic:

TableOperation retrieveOperation = TableOperation.Retrieve<SomeDomainModelType>(partitionKey, rowKey);

My question is how can I parameterise <SomeDomainModelType> so that I can use the method with any type in the domain model ? Any ideas?

Review the C# Programming Guide on Generics , specifically the Generic Methods section. Basically, define a Generic Method that can take an ITableEntity:

    public async Task<TableResult> Retrieve<T>(string tableReference, string partitionKey, string rowKey) where T : ITableEntity
    {
        var tableClient = storageAccount.CreateCloudTableClient();
        var table = tableClient.GetTableReference(tableReference);
        TableOperation retrieveOperation = TableOperation.Retrieve<T>(partitionKey, rowKey);
        TableResult retrievedResult = await table.ExecuteAsync(retrieveOperation);
        return retrievedResult;
    }

Actually, you can return retrievedResult.Result as an entity directly:

    public async Task<TEntity> Retrieve<TEntity>(string tableReference, string partitionKey, string rowKey) : where TEntity : ITableEntity
    {
        var tableClient = storageAccount.CreateCloudTableClient();
        var table = tableClient.GetTableReference(tableReference);
        TableOperation retrieveOperation = TableOperation.Retrieve<TEntity>(partitionKey, rowKey);
        TableResult retrievedResult = await table.ExecuteAsync(retrieveOperation);
        return (TEntity)retrievedResult.Result;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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