aws-sdk-net: 'DynamoDbContext.LoadAsync' does not respect 'DynamoDBOperationConfig.IndexName'
Description
When using the LoadAsync method on IDynamoDbContext to load an entity using a secondary global index, I’m getting unexpected behavior: an InvalidCastException is being thrown.
Switching the exact same call to a QueryAsync fixes the problem.
I believe LoadAsync is not respecting the IndexName property on the configuration object and is using the primary index for all searches. Either the API is incredibly misleading (as it allows you to pass this unused value) or there is a bug there.
Reproduction Steps
- Create a table with a primary and a secondary index
- Map the primary key to a
Guidproperty - Map the secondary key to a
stringproperty
[DynamoDBTable("Somethings")]
internal sealed class Something
{
[DynamoDBHashKey]
public Guid? Id { get; set; }
[DynamoDBGlobalSecondaryIndexHashKey]
public string? Name { get; set; }
}
- Try to use
LoadAsyncwith astringkey and passnew DynamoDBOperationConfig { IndexName = <Name_Of_Secondary_Index> }as options
await dynamoDBContext.LoadAsync<Something>("someName", new DynamoDBOperationConfig { IndexName = "Name-index" });
- An
InvalidCastExceptionis thrown - Replace the
LoadAsynccall withQueryAsync, and it works as expected:
var query = dynamoDBContext.QueryAsync<Something>("someName", new DynamoDBOperationConfig { IndexName = "Name-index" });
await query.GetNextSetAsync();
Logs
System.InvalidCastException: Unable to cast object of type ‘System.String’ to type ‘System.Guid’. at Amazon.DynamoDBv2.Converter`1.TryTo(Object value, Primitive& p) at Amazon.DynamoDBv2.Converter.TryToEntry(Object value, DynamoDBEntry& entry) at Amazon.DynamoDBv2.Converter.ToEntry(Object value) at Amazon.DynamoDBv2.DynamoDBEntryConversion.ConvertToEntry(Type inputType, Object value) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.ToDynamoDBEntry(SimplePropertyStorage propertyStorage, Object value, DynamoDBFlatConfig flatConfig, Boolean canReturnScalarInsteadOfList) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.ToDynamoDBEntry(SimplePropertyStorage propertyStorage, Object value, DynamoDBFlatConfig flatConfig) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.ValueToDynamoDBEntry(PropertyStorage propertyStorage, Object value, DynamoDBFlatConfig flatConfig) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.MakeKey(Object hashKey, Object rangeKey, ItemStorageConfig storageConfig, DynamoDBFlatConfig flatConfig) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.LoadHelperAsync[T](Object hashKey, Object rangeKey, DynamoDBOperationConfig operationConfig, CancellationToken cancellationToken) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.LoadAsync[T](Object hashKey, DynamoDBOperationConfig operationConfig, CancellationToken cancellationToken)
Environment
- SDK Version:
AWSSDK.CoreVersion=“3.5.1.39” - Package Version:
AWSSDK.DynamoDBv2Version=“3.5.3.3” - OS Info: Windows 10
- Build Environment Visual Studio 2019 16.8.1
- Targeted .NET Platform: Net Core 3.1
Resolution
- 👋 I can/would-like-to implement a fix for this problem myself
I belive LoadAsync should be changed to respect the index being passed as a parameter and use the object hashKey against that.
This is a 🐛 bug-report
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 2
- Comments: 23 (10 by maintainers)
Just spent a day banging my head into the wall trying to
LoadAsync()from a GSI having only a hash (but no sort) key which means there must be exactly one result matching the key. Having to useQueryAsync().GetRemainingAsync().Single()in such case is not very intuitive.Incorrect. The problem I’m having is not with the primary key (which is mapped as
Guidin C# code) but with the hash key for the secondary index, which isstringon both ends.I understand that, however the
Guidprimary key is working fine for me without having to create any converters. I think you should probably update your documentation to clarify the behavior aroundGuids in the Object Persistence Model, since they appear supported even though they are not listed there.I understand the error, but I don’t understand why it is attempting to perform that conversion in the first place. The type it should be attempting to cast to for the secondary index is
string, notGuid: I’m not performing an operation on the primary index here when specifyingIndexName.Now this is where it gets incredibly misleading then. The
LoadAsyncAPI names the first parameterhashKey, notprimaryKey. Following that nomenclature, one would understand it is “the hashkey for the index being searched”, since:If it truly is referring to the primary hashkey, then the API is incredibly misleading an needs work, in my opinion. Especially when directly compared to “sibling” APIs like
QueryAsync, which takes the same parameters, but actually works on the index you specify and not only on the primary index.From the API surface, it would appear that
LoadAsyncshould work on my scenario, but it doesn’t. As I mentioned in the OP, I think either the API should be changed to support the scenario, or it should prohibit you from passing an index name into the method. The former is preferred in my view for API consistency (working similarly toQueryAsync).We’ve merged #3421 into the
v4-developmentbranch, which includes a new set of operation-specific config objectsLoadConfig,SaveConfig,QueryConfig, etc. This should help avoid confusion aboutIndexNameand other properties that only apply to a subset of operations moving forward.We’ve marked the methods that take
DynamoDBOperationConfigas deprecated in V4, but are not planning to remove them entirely yet. We may do so in a future major version.We’re still working on getting preview packages published, you can track overall V4 progress in #3362. We’ll leave this issue open until at least V4 hits GA.
The V4 preview is out, please let us know if you find any issues with the new operation-specific config objects.
For the short term, we’ve clarified the
Load/LoadAsyncdocumentation starting in DynamoDBv2 v3.7.303.9 via #3320 to explain that 1) it callsGetItemunder the hood, which relies on the primary key and 2)IndexNameon the config does not influence which item is loaded.Longer term, we would like to make the change @julealgon suggested above - move away from the “shared”
DynamoDBOperationConfigtowards operation-specific configs that only contain applicable settings for each. You may have noticed thev4-developmentbranch, this is on our list of desired DynamoDB changes along with the interface/mockability issues.Wow, I just spent hours trying to work out what I was doing wrong! This really needs to be included in the documentation if it’s not going to be fixed. It would’ve saved me so much headache!
Needs review on how we could implement this documentation change.
Thank you @normj for the information.
If you are not willing to change the behavior of the API, perhaps you could introduce new overloads, with a tighter config model (containing only the settings that make sense for any given operation) while retaining the old overload as-is, but marking it as
deprecated. That would allow you to slowly phase it out and replace with the newer, more robust one.Another potential option would be to actually throw an exception at runtime when an invalid setting is passed into the call. I’d rather get an exception that tells me why that setting cannot be used, than get “wrong results” as is happening right now.
Anyways, very unfortunate to have such a misleading API stuck in place. I’ll probably need a significant comment block in my code to explain this anomaly and justify using the
Querysyntax in my repository implementation. I hope you can look back at this at some point and rethink the strategy (maybe implement an EF provider instead of a custom model, like CosmosDB does and some paid providers provide). Clearly, the “wheel reimplementation” here created unnecessary problems for consumers.