0

データベースに2つのテーブルがあります.1つはレシピ用、もう1つは食材用です。特定のレシピが削除されると、すべての成分も消えてしまいます。カスケードアトリビュートを設定して1対多のリレーションシップを宣言しましたが、いくつかのレシピを削除しても関連する成分は削除されません。削除カスケードが機能しない

ここに私のテーブルがある:これは私の削除操作され

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); 
     } 
    } 

は私が間違って何をしているのですか?

答えて

1

カスケード操作は、メモリ内のオブジェクトに対してのみ機能します。特定のシナリオでは、Getメソッドを使用してデータベースから1つのオブジェクトを取得しています。カスケード操作では、メモリ内のすべての関係が削除されますが、現在は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); 
+0

現在メモリにあるオブジェクトを削除するにはどうすればよいですか?また、私がこの権利を得ている場合、私が現在操作しているオブジェクトは記憶に残るでしょう、そうですか?私はこれまでこれをやっていました:database.Delete (RecipeID);それが動作していなかったので、私はそれを試してGetメソッドに変更しました。このクエリは、最初にオブジェクトをメモリから取得しますか? – Tehreem

+0

ああ、それを働いた。そして、メモリ問題のすべてのオブジェクトを得た!ありがとう。 – Tehreem

関連する問題