我有一个应用程序,其中使用 SQLiteExtensions 和以下模型:
[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.All)]
public List<FoodSelection> SelectedFoods { get; set; } = new List<FoodSelection>();
public DateTime DateLastSaved { get; set; } = DateTime.Now;
}
[Table("Foods")]
public class Food
{
[PrimaryKey, AutoIncrement] // Primary Key already indexed in Table
public int Id { get; set; }
[Unique] // Primary Key combined with ID
public string Name { get; set; }
public string Brand { get; set; }
}
[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; }
[ManyToOne(CascadeOperations = CascadeOperation.All)] // Many to one relationship with SavedMeal
public SavedMeal SavedMeal { get; set; }
public FoodSelection() : base()
{
}
public FoodSelection(Food foodItem) : base()
{
Id = foodItem.Id;
Name = foodItem.Name;
Brand = foodItem.Brand;
}
public bool IsSelected { get; set; } = false;
private int _min = 0;
public int Min
{
get => _min;
set
{
_min = value;
//NotifyPropertyChanged();
NotifyPropertyChanged(nameof(IsValid));
}
}
private int _max = 0;
public int Max
{
get => _max;
set
{
_max = value;
//NotifyPropertyChanged();
NotifyPropertyChanged(nameof(IsValid));
}
}
public bool IsValid { get => Max >= Min; }
}
在我的 DatabaseService 中,我有一个 Init 方法和一个 UpdateMeal(...) 方法:
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>();
await Database.CreateTableAsync<Food>();
}
public static async Task UpdateMeal(SavedMeal mealItem)
{
await Init();
await Database.UpdateWithChildrenAsync(mealItem);
}
名称如“午餐”的 SavedMeal 包含一个列表,该列表基本上是相应午餐的组成部分(例如鸡肉、汤、沙拉)。只是作为背景。
当我更新保存的膳食时,我还想更新数据库中的食物选择。我希望关系和约束是这样正确的。
无论如何,当我在用餐时执行 UpdateWithAllChildrenAsync(...) 时,我的约束不会更新,并且我看不到表 FoodSelections 中的更改。我检查了 SavedMeal 是否具有用于更新的正确 ID(主键),并且列表也具有我要保存的新列表。
我也尝试过
await Database.InsertOrReplaceWithChildrenAsync(mealItem, true);
也没有成功。
我的代码中是否有任何问题导致表格无法正确更新?
您得到答案了吗?我对 oneToone 也有同样的问题