Delete related entities

Posts   
 
    
Arkej
User
Posts: 4
Joined: 07-Sep-2009
# Posted on: 07-Sep-2009 12:28:01   

Hello, I'm new to LLBLGenPro and I would like to know what is the best way to delete an entity and its related entities. My case follows: I have a CabinetEntity and a DoorEntity and a m:n relation between them realised in the db by an intermediate entity CabinetsDoorsEntity. Now, when I try to delete a CabinetEntity I get stoped by the relation to the CabinetsDoorsEntity - cause it is referenced there. Likewise if I try to delete the DoorEntity, I can't - it is also refrenced in the PK of the CabinetsDoorsEntity. How can I specify that when I delete a Cabinet I also want all the records referencing that cabinet in CabinetsDoors to be deleted?

I'm using adapter mode...

             using (DataAccessAdapter da = new DataAccessAdapter(true))
            {
                EntityCollection<CabinetsEntity> toDel = new EntityCollection<CabinetsEntity>();
                da.FetchEntityCollection(toDel, null);
                foreach (CabinetsEntity cab in toDel)
                {
                    da.FetchEntityCollection(cab.CabinetsDoors, cab.GetRelationInfoCabinetsDoors());
                    da.DeleteEntity(cab);
                }
                da.DeleteEntityCollection(toDel);
            }
Walaa avatar
Walaa
Support Team
Posts: 14993
Joined: 21-Aug-2005
# Posted on: 07-Sep-2009 12:44:36   

Personally I always use Cascading deletes in the database, and it saves me big time.

But if you want to do it in code, then you'd better use a Transaction, then delete all entities in the intermediate table based on some filter (say CabinetId), you may use adapter.DeleteEntitiesDirectly(...), better than fetching the entities first. Then in the same transaction you should delete the main entity (CabinetEntity).

Arkej
User
Posts: 4
Joined: 07-Sep-2009
# Posted on: 07-Sep-2009 13:53:50   

Ok, thanks I'll use db cascades. In the example I've used fetch cause I've tried to load the entire object graph to see if then it will delete the relations. I've noticed that DeleteEntitiesDirectly will not delete the supertype record in db. Exmpl: Cabinet is a Device and I have them in TargetPerEntity but if I use DeleteEntitiesDirectly and delete cabinetEntities, records in device table are not deleted. It works if I load the entitiescollection and then use DeleteEntityCollection. Again I guess I could use db cascades.