2016-06-13 95 views
0

我在我的數據庫中有兩個表,一個用於配方,另一個用於他們的配料。當一個特定的食譜被刪除時,我希望它的所有成分都消失了。我已經聲明瞭與cascade屬性集的一對多關係,但是當我刪除一些配方時,它並沒有刪除相關的成分。刪除級聯不工作

這裏是我的表:

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方法從數據庫獲取單個對象,並且級聯操作將刪除所有內存中的關係,目前這不是因爲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