首页 > 解决方案 > 在运行时识别派生类所属的数据库集的更好方法

问题描述

我有这种方法可以从我的 EF 上下文中删除缝纫卡。基本上我有一个主要的 SewingCard 类和大约 15 个从 SewingCard 派生的类。所有这些类都有自己的 DbSet。我希望此方法接受一个参数,该参数是 SewingCard 衍生产品的混合类型列表。所以当我写这个函数时,我真的不知道什么类型的缝纫卡会被移除,除了它是一个缝纫卡。我想到了使用反射,我做到了,它奏效了。你可以看到下面的代码。但我认为有些事情可以做得更好。例如我在做

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

但我想这样做

dbSet.Remove(sewingCard)

以下是我当前的该方法代码

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 });
    }
}

我试图将 dbSet 传递为,IDbSet<dynamic>但这似乎对我不起作用。我可能做错了什么。当我尝试强制转换时,dbSet 最终为空。

标签: c#entity-frameworkreflection

解决方案


你不能这样做:

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


推荐阅读