在运行时标识派生类所属的dbset的更好方法

时间:2018-09-21 09:22:07

标签: c# entity-framework reflection

我有这种方法可以从我的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最终为null。

1 个答案:

答案 0 :(得分:5)

你不能做

n=10;
k=3;
A = rand(n);
idx = diagidx(n,k);

A(idx) = 1:(n-k);

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