I have the following two Classes. When I Save A with multiple Items (B) in it, I get the expected result. But when I save changes to A, such as an empty List of Items(B) I would expect that all elements in table B automatically get deleted because they are not referenced anywhere (Query them separately is not intented). Instead the Foreign Key(IDofA) of every item is set to Null in the table. In my case this is leading to an endless growing Table (B) because some Objects of A are never deleted, just updated.
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);
});
}
Updating an element will never result in deleting children objects by design. Performing destructive operations on a table just by updating another is not a good idea. Your endless growing table problem can be solved just by deleting elements that are not referenced anymore:
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');
});
}