在运行时标识派生类所属的数据库集的更好方法



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

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 最终变为空。

你不能这样做:

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

相关内容

最新更新