我的数据库中有两个表,一个用于配方,另一个用于配料。当一个特定的食谱被删除时,我希望它的所有成分都消失了。我已经声明了与级联属性集的一对多关系,但是当我删除一些配方时,它不会删除相关的成分。
以下是我的表格:
public class Recipe_Model
{
[PrimaryKey AutoIncrement]
public int RecipeID { get; set; }
public string RecipeName { get; set; }
public double RecipeCost { get; set; }
public double ServingsNo { get; set; }
public double CostPercent { get; set; }
public double SellingPrice { get; set; }
public double CostPerServing { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)] // One to many relationship with Ingredients
public ObservableCollection<Ingredients_Model> Ingredients { get; set; }
}
public class Ingredients_Model
{
[PrimaryKey AutoIncrement]
public int IngredientID { get; set; }
[ForeignKey(typeof(Recipe_Model))]
public int RecipeID { get; set; }
public string IngredientName { get; set; }
public string UsedUnit { get; set; }
public string PurchasedUnit { get; set; }
public double QuantityUsed { get; set; }
public double QuantityPurchased { get; set; }
public double PurchasePrice { get; set; }
public double IngredientCost { get; set; }
}
这是我的删除操作:
public void DeleteRecipe()
{
using (SQLiteConnection database = DependencyService.Get<ISQLite>().GetConnection())
{
var recipe = database.Get<Recipe_Model>(RecipeID);
database.Delete(recipe, true);
}
}
我做错了什么?
答案 0 :(得分:1)
级联操作仅适用于内存中的对象。在您的特定方案中,您将通过Get
方法从数据库中获取单个对象,并且级联操作将删除所有内存中关系,由于Ingredients
属性为null
,因此目前无关系。
如果你还没有内存中的对象,加载它们只是为了获取标识符来删除它们,这正是级联删除所做的:
// This would work as it loads children to memory, but it's inefficient
var recipe = database.GetWithChildren<Recipe_Model>(RecipeID);
database.Delete(recipe, true);
相反,我建议您手动删除它们:
database.Execute("DELETE FROM [Ingredients_Model] WHERE [RecipeID] == ?", recipe.Id);
database.Delete(recipe);