我需要对数据库上下文中的所有表运行查询。我相信你可以通过这样做来遍历上下文选项卡
foreach (var entityType in context.Model.GetEntityTypes()) {
}
但是,我没有看到一种在entityType上运行linq查询的方法。有没有办法做到这一点。
发布于 2019-07-12 21:59:54
假设您的代码返回一组与DbSet<T>
定义中的条目相关的类型,
也就是说我假设
IEnumerable<Type> entityTypes = context.Model.GetEntityTypes();
您可以设置一个可以使用该类型调用的方法,并简单地在其DbSet上使用FirstOrDefault。
我不确定你的领域的确切范围是什么,所以其中一些假设你需要调整以适应你的架构。
public class ThisClassReference
{
// It wasn't provided, so this is just to show the containing method area,
// and also provide reference to the current executing object instance,
// which we will need to reference below
public void YourExecutingMethod()
{
// Iterate through the set of entity types
foreach (var entityType in context.Model.GetEntityTypes()) {
// We need the class reference to construct the method call
Type ThisClassReference = typeof(ThisClassReference);
// We need the name of generic method to call using the class reference
MethodInfo mi = ThisClassReference.GetMethod("FirstOrDefaultGeneric", BindingFlags.Instance | BindingFlags.NonPublic);
// This creates a callable MethodInfo with our generic type
MethodInfo miConstructed = mi.MakeGenericMethod(entityType);
// This calls the method with the generic type using Invoke
miConstructed.Invoke(this, null);
}
}
// Once called use the generic type to access the first result in the DbSet from your context.
private void FirstOrDefaultGeneric<T>()
{
var unUsed = context.Set<T>.FirstOrDefault();
}
}
弄清楚如何将这些调用转换为异步调用,并为自己节省大约40毫秒的每种类型。
发布于 2019-07-14 03:52:07
我能够让这段代码正常工作:
PropertyInfo[] properties = context.GetType().GetProperties();
foreach (PropertyInfo property in properties) {
var prop = context.GetType().GetProperty(property.Name).GetValue(context, null);
var table = prop as IEnumerable<BaseDbModel>;
if(table != null) {
var row = table.Select(a => a.createdDttm).FirstOrDefault();
}
}
https://stackoverflow.com/questions/57013800
复制相似问题