获取DbContext Entity Framework Core 2.1中的实体模型列表 [英] Get List of Entity Models in DbContext Entity Framework Core 2.1

查看:91
本文介绍了获取DbContext Entity Framework Core 2.1中的实体模型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法来获取DbContext中所有实体模型的列表。例如,如果我在C#中定义了两个称为客户和发票的模型,这些模型首先通过代码创建了EF实体和一个数据库,那么现在我该如何查询DbContext以获得包含客户和发票的列表-即,在这种情况下的所有实体?我希望能够调用一个返回所有实体列表的方法,而不是返回数据,而只是实体列表。

I'm trying to find a way to get a List of all of the entity models in my DbContext. For instance, if I have two models called Customer and Invoice defined in C# which through code-first I created EF entities and a database, how do I now query the DbContext to get a List that has Customer and Invoice in it -- i.e., all of the entities in that context? I want to be able to call a method that returns a List of all the entities -- not the data, just a list of the entities.

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

It seems to me this should be so easy, but either it is not easy or I am missing something -- probably the latter. ;-).

有人可以指出正确的方向吗?谢谢!!

Could someone please point me in the right direction? Thanks!!

推荐答案

您可以使用模型属性以获取关联的 IModel ,然后 GetEntityTypes 方法来枚举所有 IEntityType 。的 ClrType 属性 IEntityType 将为您提供关联的类类型,例如

You can use Model property to get the associated IModel, then GetEntityTypes method to enumerate all IEntityTypes. ClrType property of IEntityType will give you the associated class type, e.g.

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

IEntityType 具有许多有用的属性,并且(扩展名)获取有关主键/备用键,外键,导航,属性等信息的方法(如果需要)。

IEntityType has many useful properties and (extension) methods for getting information about the primary/alternate keys, foreign keys, navigations, properties etc. in case you need them.

这篇关于获取DbContext Entity Framework Core 2.1中的实体模型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆