如何遍历数据库上下文中的所有表并查询数据

时间:2019-07-12 20:41:07

标签: entity-framework .net-core entity-framework-core

我需要在数据库上下文中的所有表上运行查询。我相信您可以通过

遍历上下文选项卡
foreach (var entityType in context.Model.GetEntityTypes()) {

}

但是,我没有看到在entityType上运行linq查询的方法。有办法吗?

2 个答案:

答案 0 :(得分:1)

假设您的代码返回了一组与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();
    }

}

奖金点在于弄清楚如何将这些调用转换为异步调用,并为每种类型节省大约40ms的时间。

答案 1 :(得分:0)

我能够使此代码正常工作:

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();
                    }
                }