SQLite-Extensions creating empty entries after Update (data inconsistencies)

24 Views Asked by At

I have the following classes to store meals with SQLiteExtensions. When I store a SavedMeal named M1 having a List of e.g. 3 SelectedFoods (e.g. Chicken, Potatoes and Salad) it is stored in my database successfully - great

[Table("SavedMeals")]
public class SavedMeal
{
    [PrimaryKey, AutoIncrement]     // Primary Key already indexed in Table
    public int Id { get; set; }

    [Unique]                        // Primary Key combined with ID
    public string Name { get; set; }


    [OneToMany(CascadeOperations = CascadeOperation.CascadeInsert | CascadeOperation.CascadeRead | CascadeOperation.CascadeDelete)]
    public List<FoodSelection> SelectedFoods { get; set; } = new List<FoodSelection>();
}
[Table("FoodSelections")]
public class FoodSelection : Food
{
    [PrimaryKey, AutoIncrement]     // Primary Key already indexed in Table
    public new int Id { get; set; }

    [ForeignKey(typeof(SavedMeal))]     // Specify the foreign key
    public int SavedMealId { get; set; }


    public new string Name { get; set; }                
}
static async Task Init()
{
    if (Database is not null)
    {
        return;
    }

    Database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);

    await Database.CreateTableAsync<FoodSelection>();
    await Database.CreateTableAsync<SavedMeal>();
}
public static async Task AddMeal(SavedMeal mealItem)
{
    await Init();

    await Database.InsertWithChildrenAsync(mealItem, true);
}
public static async Task UpdateMeal(SavedMeal mealItem)
{
    await Init();

    await Database.UpdateWithChildrenAsync(mealItem);
}

When I use UpdateWithChildrenAsync(...) to update M1 which is now only having a List of 2 SelectedFoods (e.g. Chicken and Salad), I can still see Potatoes in my Database but not referenced anymore by M1.

Why is that and is there a good way to prevent that and keep the consistency? I thought these Cascade-Attributes should help keeping the database consistent?

0

There are 0 best solutions below