C#C
C#13mo ago
5 replies
Zoli

Resolving Entity Framework Core Tracking Issues with Shared Relationships in .NET MAUI and SQLite

Context:
I am developing a .NET MAUI application using Entity Framework Core with SQLite as the local database provider. The application involves managing workouts, exercises, and exercise variants. Below is a detailed explanation of my workflow and the issue I am encountering:

Workflow
Saving Default Exercise Variants Locally
Upon user login, I fetch a predefined list of exercise variants (with fixed IDs) and save them locally using the following code:

await _dbContext.AddRangeAsync(exerciseVariants, cancellationToken);
await _dbContext.SaveChangesAsync().ConfigureAwait(false);


Retrieving All Exercise Variants
To retrieve all locally stored exercise variants, I use the following query:

var allExerciseVariants = await dbContext.ExerciseVariant
    .AsNoTracking()
    .ToListAsync(cancellationToken);


Creating and Saving a Workout
When creating a workout, I define it with associated exercises as shown below:

var workout = new Workout()
{
    Title = "Test"
};

var exercises = new List<Exercise>()
{
    new Exercise()
    {
        Note = "Test note",
        ExerciseVariant = allExerciseVariants.FirstOrDefault(), // Selecting the first variant for testing purposes
    }
};

workout.Exercises.AddRange(exercises);

await dbContext.Workout.AddAsync(workout);
await dbContext.SaveChangesAsync();


Continue in the comment section
Was this page helpful?