4
votes

I'm writing a method that retrieves an entity from an Azure Table Storage service. I need to return the entity as type User rather than as TableResult. The following compiles, but always returns Null:

var partitionKey = "user";

            var retrieveOperation = TableOperation.Retrieve<TableEntity>(partitionKey, userName);
            var result = _table.Execute(retrieveOperation);

            if (result == null)
            {
                return null;
            }

            return result.Result as User;

I'm assuming this is because the cast from TableResult to User doesn't work for some reason. Casting it like (User)result.Result actally throws an error at runtime. I've seen an example using Linq on a list of entities, but how do you cast a single result?

1

1 Answers

5
votes

If your entity User inherits from TableEntity (or implements ITableEntity) :

public class User : TableEntity { }

you can specify the type of the result:

var retrieveOperation = TableOperation.Retrieve<User>(partitionKey, userName);

So in your case, it will look like this:

var partitionKey = "user";
var retrieveOperation = TableOperation.Retrieve<User>(partitionKey, userName);
var result = _table.Execute(retrieveOperation);
if (result == null)
{
    return null;
}
return result.Result as User;

Another approach is to use the DynamicTableEntity class:

var partitionKey = "user";
// The default result type is DynamicTableEntity
var retrieveOperation = TableOperation.Retrieve(partitionKey, userName);
var result = _table.Execute(retrieveOperation);
if (result == null)
{
    return null;
}
return result.Result as DynamicTableEntity;