CommunityToolkit / CommunityToolkit/dotnet
Retrieving InvalidOperationException when inserting new item to collection
- Dominant language
- C#
- Stars
- 3.8k
- Forks
- 400
- PR merge metrics
- No merged PRs in 30d
Description
### Describe the bug
First of all, I'm using the [JsonFlatFileDataStore ](https://github.com/ttu/json-flatfile-datastore) package.
I'm trying to insert a new item to a collection and the insertion works, but the `CommunityToolkit.Mvvm.dll` throws a `System.InvalidOperationException`.
```csharp
// THIS IS DEFINED IN A SEPARATE ClassLibrary targeting NET 6 with JsonFlatFileDataStore installed
public async Task CreateReference(ReferenceObject reference)
{
if (!_service.IsDataServiceInitialized())
return -1;
// Get ReferenceObject collection
var collection = _service.DataStore!.GetCollection();
try
{
bool result = await collection.InsertOneAsync(reference); // HERE IS WHERE THE ERROR IS THROWN
if (result)
return reference.Id;
}
catch (Exception ex)
{
throw;
}
return -1;
}
```
The message to call the previous class is:
```csharp
public async void Receive(AddReferenceMessage message)
{
var newId = await _referenceManager.CreateReference(message.Value);
message.Value.SetNewId(newId);
ReferenceCollection.Add(message.Value);
message.Reply(newId);
}
```
(`AddReferenceMessage` inherits from `AsyncRequestMessage`)
I'm using a custom AsyncCommand class where I pass the `IMessenger` in the constructor to call the message:
```csharp
...
try
{
int newId = await _messenger.Send(new AddReferenceMessage(viewModel._reference));
_messenger.Send(new ShowMainSnackBarMessage($"Successfully added reference {viewModel.Name}"));
_viewModel.LoadReferencesCommand.Execute(null);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message); // HERE I CATCH THE ERROR
}
...
```
### Regression
_No response_
### Steps to reproduce
```text
Environment:
NET 6
CommunityToolkit.Mvvm 8.1
JsonFlatFileDataStore 2.4.1
```
### Expected behavior
To retrieve correctly the new id of the inserted object, as the object is properly inserted into the JSON file and a new id is assigned to the new object.
### Screenshots
_No response_
### IDE and version
VS 2022
### IDE version
_No response_
### Nuget packages
- [ ] CommunityToolkit.Common
- [ ] CommunityToolkit.Diagnostics
- [ ] CommunityToolkit.HighPerformance
- [X] CommunityToolkit.Mvvm (aka MVVM Toolkit)
### Nuget package version(s)
8.1.0
### Additional context
_No response_
### Help us help you
Yes, but only if others can assist
Contributor guide
Assessment
This issue has not been assessed yet.