我有这种方法可以从我的EF上下文中删除缝纫卡.Basicaly我有一个主要的SewingCard课程和大约15个来自SewingCard的课程.所有这些类都有自己的DbSet.我希望这个方法接受一个参数,该参数是混合类型的SewingCard衍生物的列表.因此,当我写这个功能时,我真的不知道什么类型的缝纫卡会被移除,除了它是一张缝卡.我想过使用反射,我做了它,它的工作原理.你可以看到下面的代码.但我认为有些事情可以做得更好.例如即时通讯
var removeMethod = dbSet.GetType().GetMethod("Remove");
removeMethod.Invoke(dbSet, new[] { sewingCard });
Run Code Online (Sandbox Code Playgroud)
但我想这样做
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 = …Run Code Online (Sandbox Code Playgroud)