CommunityToolkit / dotnet

.NET Community Toolkit is a collection of helpers and APIs that work for all .NET developers and are agnostic of any specific UI platform. The toolkit is maintained and published by Microsoft, and part of the .NET Foundation.
https://docs.microsoft.com/dotnet/communitytoolkit/?WT.mc_id=dotnet-0000-bramin
Other
2.99k stars 294 forks source link

Retrieving InvalidOperationException when inserting new item to collection #617

Open darkonl opened 1 year ago

darkonl commented 1 year ago

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

Nuget package version(s)

8.1.0

Additional context

No response

Help us help you

Yes, but only if others can assist