获取 DbContext 中的实体模型列表 Entity Framework Core 2.1

Get List of Entity Models in DbContext Entity Framework Core 2.1

我正在尝试找到一种方法来获取我的 DbContext 中所有实体模型的列表。例如,如果我在 C# 中定义了两个名为 Customer 和 Invoice 的模型,我通过代码优先创建了 EF 实体和一个数据库,那么我现在如何查询 DbContext 以获取其中包含 Customer 和 Invoice 的列表——即,该上下文中的所有实体?我希望能够调用一种方法,该方法 returns 所有实体的列表——不是数据,只是实体列表。

在我看来这应该很容易,但要么不容易,要么我遗漏了一些东西 -- 可能是后者。 ;-).

有人能给我指出正确的方向吗?谢谢!!

您可以参考文档:https://docs.microsoft.com/en-us/ef/core/querying/related-data

例如。如果您有两个 table 的博客和帖子,那么您可以获得相关的 table,如下所示。这取决于关系如何存在于两个 table 中。

您还可以添加 where 子句以仅获取选定的记录。

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .ToList();
}

您可以使用 Model property to get the associated IModel, then GetEntityTypes method to enumerate all IEntityTypes. ClrType 属性 of IEntityType 将为您提供关联的 class 类型,例如

DbContext db = ...;
var entityTypes = db.Model.GetEntityTypes().Select(t => t.ClrType).ToList();

IEntityType 有许多有用的属性和(扩展)方法,用于获取有关 primary/alternate 键、外键、导航、属性等的信息,以备不时之需。