2016-06-13 251 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