c# - 在运行时识别派生类所属的数据库集的更好方法
问题描述
我有这种方法可以从我的 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 最终为空。
解决方案
你不能这样做:
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
推荐阅读
- javascript - Vanilla JS - 无限自动播放滑块
- python - 将脚本导入另一个脚本以编辑变量时出现 ModuleNotFoundError
- flutter - 使用 Riverpod 打开页面时如何进行多个异步调用?
- node.js - Teams Bot 如何收听来电?
- python - 基于日期时间对象添加季节列时遇到问题
- r - R - 确定符合预定义标准的配置文件(四个类别)的所有组合
- swift - UICollectionView 中 MTKView 重叠的单元格
- spring - Spring-boot:将@EnableWebMvc 支持添加到现有的@EnableWS 应用程序?
- reporting-services - 自定义表达式值的 SQL Server Report Builder submation
- r - 合并来自大约的数据。R中的70个表