Better way of identifying the dbset that derived classes belong to at runtime

Viewed 71

I have this method that removes sewing cards from my EF context. Basicaly i have a main SewingCard class and around 15 classes that derive from SewingCard. All of those classes have their own DbSets. I want this method to accept a parameter which is a list of mixed types of SewingCard derivatives. So when i write this function i dont really know what type of sewing card will be removed, except that its a sewing card. I thought of using reflection and i did it and it works. You can see the code below. But i think some things could be done better. For example im doing

var removeMethod = dbSet.GetType().GetMethod("Remove");
removeMethod.Invoke(dbSet, new[] { sewingCard });

but i would want to do it like this

dbSet.Remove(sewingCard)

Below is my current code of that method

public void RemoveSewingCards(List<SewingCard> sewingCards, ApplicationDbContext context)
{
    //getting the properties of context which holds SewingCards
    var dbSets = context.GetType().GetProperties()
            .Where(p => Attribute.IsDefined(p, typeof(IncludeSewingCards))).ToList();

    //iterating through sewingCards list
    foreach (var sewingCard in sewingCards)
    {               
        var sewingCardType = sewingCard.GetType();

        // getting the correct dbSet for the correct sewingCard
        var dbSet = dbSets.FirstOrDefault(d => d.PropertyType.GetGenericArguments()
                .Any(a => a == sewingCardType))
                .GetValue(context);

        //getting the Remove method of dbSet
        var removeMethod = dbSet.GetType().GetMethod("Remove");
        //calling the method
        removeMethod.Invoke(dbSet, new[] { sewingCard });
    }
}

I was trying to pass dbSet as IDbSet<dynamic> but that doesnt seem to work for me. I was probably doing something wrong. the dbSet ends up being null when i try to cast it.

1 Answers

Can't you do:

public void RemoveSewingCards(List<SewingCard> sewingCards, ApplicationDbContext context)
{
    //iterating through sewingCards list
    foreach (var sewingCard in sewingCards)
    {               
        var sewingCardType = sewingCard.GetType();
        var dbSet = context.Set(sewingCardType).Remove(sewingCard);
    }
}

https://msdn.microsoft.com/en-us/library/gg679544(v=vs.113).aspx

Related