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).
You could try something like this:
return (Entity)retrievedResult.Result;
class Entity : TableEntity
{
public string PartKey => PartitionKey;
public string RowKey => RowKey;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With