Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting the Result of TableOperation.Retrieve

Tags:

c#

azure

I recently got into C# / Azure and have a small problem that I'd like to work out. The application works as intended but I'd like to refactor a bunch of classes because I'm sure that there is a simpler solution.

I currently have a bunch of functions to retrieve Entities from the Azure that only vary in the Type that gets retrieved, but optimally I'd only want one class like so:

public static Object Do(string RowKey, string partitionKey, string tableName)
{
    var theTable = Connect.Initialize(tableName);
    var retrieveOperation = TableOperation.Retrieve(
                                      Base64.EncodeTo64(partitionKey),
                                      Base64.EncodeTo64(RowKey));

    var retrievedResult = theTable.Execute(retrieveOperation);

    if (retrievedResult.Result != null) {
        return retrievedResult.Result;
    }
     throw new ArgumentException(
                 String.Format("{0} not found in the Table", RowKey));
}

This, in itself, works and retrieves the required entities. However, I cannot cast the returned Object without an Error.

The Object Type that I want to cast it to implements the TableEntity-Type and matches the Result out of the table.

I know that I can cast it in the sense of

TableOperation.Retrieve<Type>(...)

but I'd really like to use a single function for this purpose which requires me to cast it on calling the function.

I suspect that the problem is related to the fact that the Result is of the Type DynamicTableEntity but I am pretty lost as to why.

Is there any way to solve this problem elegantly / is there a way to establish a parameter that holds the Type that I want as a result? (I tried it with "Type ..." but that doesn't work).

like image 570
user2436607 Avatar asked May 30 '13 12:05

user2436607


2 Answers

You could try something like this:

return (Entity)retrievedResult.Result;

class Entity : TableEntity
{
    public string PartKey => PartitionKey;
    public string RowKey => RowKey;
}
like image 145
Jnr Avatar answered Oct 25 '22 15:10

Jnr


Try this, Specify TEntity as TableEntity explicitly then cast it to generalized one

public async Task<TEntity> Get<TEntity>(string tableName, string partitionKey, string rowkey) where TEntity : TableEntity, new()
    {
        var table = this._tableClient.GetTableReference(tableName);
        var result = await table.ExecuteAsync(TableOperation.Retrieve<TEntity>(partitionKey, rowkey));
        return (TEntity)result.Result;
    }
like image 29
Juber Pinjari Avatar answered Oct 25 '22 16:10

Juber Pinjari