Get List of Entity Models in DbContext Entity Framework Core 2.1

Kevin picture Kevin · Jan 14, 2019 · Viewed 14.5k times · Source

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!!

Answer

Ivan Stoev picture Ivan Stoev · Jan 14, 2019

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 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.