Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get List of Entity Models in DbContext Entity Framework Core 2.1

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

like image 956
Kevin Avatar asked Jan 14 '19 19:01

Kevin


1 Answers

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.

like image 118
Ivan Stoev Avatar answered Sep 20 '22 09:09

Ivan Stoev