2017-01-30 22 views
0

我有以下兩個類。 當我將多個項目(B)保存在其中時,我會得到預期的結果。 但是,當我保存對A的更改時,比如空的List of Items(B),我希望表B中的所有元素都會自動被刪除,因爲它們在任何地方都沒有被引用(分別查詢它們並不是)。 而是表中的每個項目的外鍵(IDofA)都設置爲Null。 在我的情況下,這導致無限增長的表(B),因爲A的某些對象從不刪除,只是更新。SQLite.Net擴展 - 刪除更新中的子項

public class A 
{ 
    public string Name{ get; set; } 

    [OneToMany(CascadeOperations = CascadeOperation.All)] 
    public List<B> Items { get; set; } 
} 

public class B 
{ 
    [ForeignKey(typeof(A))] 
    public string IDofA { get; set; } 
} 


//This is the Generic Save Method that I use for all the Objects 
public virtual void Save(T element) 
    { 
     CreateID(element); 
     if (!RuntimeCache.Any(x => x.ID == element.ID)) 
     { 
      RuntimeCache.Add(element); 
     } 

     element.UpdateChangeDate(); 

     RunDBQueryAsync((conn) => 
     { 
      conn.InsertOrReplaceWithChildren(element); 
     }); 
    } 

回答

0

更新元素永遠不會導致設計中刪除子對象。通過更新另一個表來執行破壞性操作不是一個好主意。你無盡的成長表問題,只需通過刪除不再被引用的元素來解決:

public virtual void Save(T element) 
{ 
    CreateID(element); 
    if (!RuntimeCache.Any(x => x.ID == element.ID)) 
    { 
     RuntimeCache.Add(element); 
    } 

    element.UpdateChangeDate(); 

    RunDBQueryAsync((conn) => 
    { 
     conn.InsertOrReplaceWithChildren(element); 
     // Delete orphaned children 
     conn.Execute("DELETE FROM B WHERE IDofA IS NULL'); 
    }); 
} 
+0

我一直希望有對於配置... 無論如何,感謝最簡單的辦法。 –