dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

Retrieving InvalidOperationException when inserting new item to collection

Open darkonl opened this issue 2 years ago • 0 comments

Describe the bug

First of all, I'm using the JsonFlatFileDataStore 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.

// THIS IS DEFINED IN A SEPARATE ClassLibrary targeting NET 6 with JsonFlatFileDataStore installed
public async Task<int> CreateReference(ReferenceObject reference)
{
    if (!_service.IsDataServiceInitialized())
        return -1;
    // Get ReferenceObject collection
    var collection = _service.DataStore!.GetCollection<ReferenceObject>();
    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:

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<int>)

I'm using a custom AsyncCommand class where I pass the IMessenger in the constructor to call the message:

...
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

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

darkonl avatar Feb 21 '23 17:02 darkonl