How to remove orphans?

Let's assume I have a class A which references a class B. B shall exist only as part of A, but not each A always has a B.



So I create something like this:





[Entity]

[Table('CLASS_A')]

[Id('FId', TIdGenerator.IdentityOrSequence)]

TClassA = class

    private

      [Column('ID', [TColumnProp.Unique, TColumnProp.Required])]

      FId: Integer;

     

      [Association([TAssociationProp.Lazy], CascadeTypeAll)]

      [ForeignJoinColumn('IDA', [TColumnProp.Required])]

      FClassB : Proxy<TClassB>;

     

     [...]



end;





[Entity]

[Table('CLASS_B')]

[Id('FId', TIdGenerator.IdentityOrSequence)]

TClassA = class

    private

      [Column('ID', [TColumnProp.Unique, TColumnProp.Required])]

      FId: Integer;

     

      [Column('IDA')]

      FIdA: Integer;

     

     [...]



end;





When I assign a new B to an A, how do I make sure that the old B - which is now an orphan - gets deleted from the database?

There is no such automatic option for that. You must do it manually by removing the orphan B.

Note that with the associaton you are doing, it's A that references B and not the opposite. Have you even tried that code? ForeignJoinColumn attribute doesn't fit here.

What you can duo is create a Many-Value Association from B to A:
      [ManyValuedAssociation([TAssociationProp.Lazy], CascadeTypeAllRemoveOrphan)] 
      [ForeignJoinColumn('IDA', [TColumnProp.Required])] 
      FClassBList : Proxy<TList<TClassB>>; 

This makes more sense, which means B objects (records) reference A objects (records). Thus if you remove a B object from A.FClassBList, they will be removed as well.

No, I haven't tried that code.



I actually had this many-to-one association before, but it turned out that I need max. 1 instance of B.



Anyway, I keep it like that but make sure in the property accessors that I have maximum one element in the list.