mardi 19 février 2019

Add cascade delete for all nested child in hierarchy chain

I would like to get the following behavior, when deleting an object from a parent level of first level, all entities "child" were deleted automatically, say I have a Library class that has a list "areas", each area has a list of "corridors", and each corridor has a "ranks" list, each rank has a list of books. Did you understand that the level is going down?

Schematic model:

Biblioteca
-----> Area
----------> Corridors
---------------> Ranks
--------------------> Book

Classes:

class Library {
    public int Id {get;set;}
    public List<Area> Areas {get;set;}
}

class Area {
    public int Id {get;set;}
    public Library Library {get;set;}
    public List<Corridor> Corridors {get;set;}
}

class Corridor {
    public int Id {get;set;}
    public Area Area {get;set;}
    public List<Rank> Ranks {get;set;}
}

class Rank {
    public int Id {get;set;}
    public Corridor Corridor {get;set;}
    public List<Book> Books {get;set;}
}

class Book {
    public int Id {get;set;}
    public Rank Rank {get;set;}
    public string Name {get;set;}
}

I wish that when I erased Library, I would erase the children that were needed within the chain, cascade. I can do this with the following code, I made all my classes inherit from a common class that I called "Registry", and that all of them had a common property called "Library", and I configured it as follows:

modelBuilder.Model.GetEntityTypes()
    .Where(t => typeof(Registry).IsAssignableFrom(t.ClrType))
    .ToList()
    .ForEach(prop =>
    {
        modelBuilder
        .Entity(prop.Name)
        .HasOne(typeof(Library), "Library")
        .WithMany()
        .OnDelete(DeleteBehavior.Cascade);
    });

I tested with a 20 classes and ran, in the created migration, all 20 entities, have an FK pointing to Library, called "LibraryId" and with the property, "onDelete: ReferentialAction.Cascade", but I have a structure with 650 classes, it is completely impracticable to be inheriting all of them from the Registry class, I think there should be a simpler and more efficient way, but I do not know how to do it ...

Aucun commentaire:

Enregistrer un commentaire