首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何遍历数据库上下文中的所有表并查询数据

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

Stack Overflow用户
提问于 2019-07-13 04:41:07
回答 2查看 1.7K关注 0票数 0

我需要对数据库上下文中的所有表运行查询。我相信你可以通过这样做来遍历上下文选项卡

代码语言:javascript
代码运行次数:0
运行
复制
foreach (var entityType in context.Model.GetEntityTypes()) {

}

但是,我没有看到一种在entityType上运行linq查询的方法。有没有办法做到这一点。

EN

回答 2

Stack Overflow用户

发布于 2019-07-13 05:59:54

假设您的代码返回一组与DbSet<T>定义中的条目相关的类型,

也就是说我假设

代码语言:javascript
代码运行次数:0
运行
复制
IEnumerable<Type> entityTypes = context.Model.GetEntityTypes();

您可以设置一个可以使用该类型调用的方法,并简单地在其DbSet上使用FirstOrDefault。

我不确定你的领域的确切范围是什么,所以其中一些假设你需要调整以适应你的架构。

代码语言:javascript
代码运行次数:0
运行
复制
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毫秒的每种类型。

票数 3
EN

Stack Overflow用户

发布于 2019-07-14 11:52:07

我能够让这段代码正常工作:

代码语言:javascript
代码运行次数: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();
                    }
                } 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57013800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档