Looking to pass entity as generic type and extract common functionality

and then through navigation property finding the child entity

You don’t need to do that manually, EF Core can do that for you using of of the available methods for Loading Related Data – eager, explicit or lazy. In this particular case eager loading is probably the most appropriate because it allows you to combine the first two steps (finding main entity and the associated child entity) in one with single database request.

Whatever method for finding child entity you choose, the generalization of the methods in question would be to provide the navigation property accessor expression (Expression<Func<TParent, TChild>>), which will be enough to perform the equivalent actions of the current code.

For instance, assuming the GlazingOrGasMaterial.Id property type is Guid and is coming from AEIMasterBase class, the body can be generalized as

public static void RemoveChild<TParent, TChild>(
    DbContext db,
    Guid parentId,
    Expression<Func<TParent, TChild>> childReference // <--
    where TParent : AEIMasterBase
    where TChild : class
    var parent = db.Set<TParent>()
        .Include(childReference) // <--
        .FirstOrDefault(p => p.Id == parentId);
    if (parent != null)
        var child = db.Entry(parent)
            .Reference(childReference) // <--
        if (child != null)

But now it can easily be seen that you don`t really need the parent entity, so the implementation could be simplified (and also become more efficient) as follows (the same method signature):

var child = db.Set<TParent>()
    .Where(p => p.Id == parentId)
    .Select(childReference) // <--
if (child != null)

In both cases, the 3 calls would be

if (requestInput.RequestType == RequestAction.EDIT)
    RemoveChild(dbContext, requestInput.DataId, (GlazingOrGasMaterial m) => m.{NavigationProperty});

where m.{NavigationProperty} is respectively m.GlazingGasMaterial, m.GlazingComplexMaterial and m.GlazingSimpleMaterial

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top