2

I have an entity structure like as below, and what I am doing here is based on input finding main entity and then through navigation property finding the child entity and then deleting child entity from child table at different places

public class GlazingOrGasMaterial : AEIMasterBase
{
    [ForeignKey("SourceOfData"), GraphQLIgnore]
    public Guid? SourceOfDataId { get; set; }
    public virtual CodeStandardGuideline SourceOfData { get; set; }
    [ForeignKey("GlazingComplexMaterial"), GraphQLIgnore]
    public Guid? GlazingComplexMaterialId { get; set; }
    [ForeignKey("GlazingSimpleMaterial"), GraphQLIgnore]
    public Guid? GlazingSimpleMaterialId { get; set; }
    [ForeignKey("GlazingGasMaterial"), GraphQLIgnore]
    public Guid? GlazingGasMaterialId { get; set; }
    public virtual GlazingComplexMaterial GlazingComplexMaterial { get; set; }
    public virtual GlazingSimpleMaterial GlazingSimpleMaterial { get; set; }
    public virtual GlazingGasMaterial GlazingGasMaterial { get; set; }
}

and below is the code for deleting that child entity

Method 1:

   if(requestInput.RequestType == RequestAction.EDIT)
    {
        var existingGlazingOrGasMaterial = dbContext.GlazingOrGasMaterials.Find(requestInput.DataId);
        if(existingGlazingOrGasMaterial != default)
        {
            var existingGasMaterial = dbContext.GlazingGasMaterials.SingleOrDefault(gasMaterial => gasMaterial.Id == existingGlazingOrGasMaterial.GlazingGasMaterialId);
            if(existingGasMaterial != default)
            {
                dbContext.GlazingGasMaterials.Remove(existingGasMaterial);
            }
        }
    }

below is the code where i am deleting that child entity

Method 2 :

    if (requestInput.RequestType == RequestAction.EDIT)
    {
        var existingGlazingOrGasMaterial = dbContext.GlazingOrGasMaterials.Find(requestInput.DataId);
        if (existingGlazingOrGasMaterial != default)
        {
            var existingComplexMaterial = dbContext.GlazingComplexMaterials.SingleOrDefault(complexMaterial => complexMaterial.Id == existingGlazingOrGasMaterial.GlazingComplexMaterialId);
            if (existingComplexMaterial != default)
            {
                dbContext.GlazingComplexMaterials.Remove(existingComplexMaterial);
            }
        }
    }

Method 3:

    if (requestInput.RequestType == RequestAction.EDIT)
    {
        var existingGlazingOrGasMaterial = dbContext.GlazingOrGasMaterials.Find(requestInput.DataId);
        if (existingGlazingOrGasMaterial != default)
        {
            var existingSimpleMaterial = dbContext.GlazingSimpleMaterials.SingleOrDefault(simpleMaterial => simpleMaterial.Id == existingGlazingOrGasMaterial.GlazingSimpleMaterialId);
            if (existingSimpleMaterial != default)
            {
                dbContext.GlazingSimpleMaterials.Remove(existingSimpleMaterial);
            }
        }
    }

below is the structure for child entities

public class GlazingSimpleMaterial 
{
    public Guid Id { get; set; }
    .....
    .....
}
public class GlazingComplexMaterial 
{
    public Guid Id { get; set; }
    .....
    .....
}
public class GlazingGasMaterial 
{
    public Guid Id { get; set; }
    .....
    .....
}

and I am looking kind of a common method where we can pass entity as generic type and do the removal, Could any one please let me know how can I achieve this?

many thanks in advance!!

4
  • What is the relationship between GlazingOrGasMaterial and GlazingComplexMaterial, GlazingSimpleMaterial, GlazingGasMaterial. For your model I understand that a GlazingOrGasMaterial can have none, one, two or the three types GlazingComplexMaterial, GlazingSimpleMaterial, GlazingGasMaterial. Is that corrrect? Nov 1, 2020 at 22:00
  • Solution will more complicated that your code. I think it will be wasting of time. Anyway, try to find child entity in one query, I do not see reason of sending two queries. Nov 1, 2020 at 22:26
  • @RodRamírez i do have one to one relation ship between each child entity to parent entity
    – kumar jain
    Nov 1, 2020 at 23:02
  • @SvyatoslavDanyliv Could you please point me in the right direction sending in one query to find child entity
    – kumar jain
    Nov 1, 2020 at 23:03

3 Answers 3

3

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) // <--
            .CurrentValue;
        if (child != null)
            db.Remove(child);
    }
}

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) // <--
    .FirstOrDefault();
if (child != null)
    db.Remove(child);

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

0
2

At first, let's speedup your query

if (requestInput.RequestType == RequestAction.EDIT)
{
    var query = 
       from m in dbContext.GlazingOrGasMaterials
       join gasMaterial in dbContext.GlazingGasMaterials on m.GlazingGasMaterialId equals gasMaterial.Id
       where m.Id == requestInput.DataId
       select gasMaterial;

    var existingGasMaterial = query.FirstOrDefault();

    if (existingGasMaterial != default)
    {
        dbContext.GlazingGasMaterials.Remove(existingGasMaterial);
    }
}
1
  • @IvanStoev, I don't see navigation property in question. I have deleted only one child entity. Nov 2, 2020 at 9:25
2

If you are going to blindly delete something, you don't need to load it from the database first;

dbContext.GlazingGasMaterials.Remove(
    new GlazingOrGasMaterials{
        Id = existingGlazingOrGasMaterial.GlazingGasMaterialId
    });

Assuming that your types implement a common interface to define their primary key, you can generalise the above;

public static void Remove<T>(this DbContext context, Guid Id) where T:IPrimaryKey, new() =>
dbContext.Set<T>.Remove(
    new T{
        Id = Id
    });

Though that doesn't simplify your code that much.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.