问题
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!!
回答1:
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.
回答2:
You can refer documetation at: https://docs.microsoft.com/en-us/ef/core/querying/related-data
For ex. If you have blogs and posts as two tables, then you can get related table as shown below. It depends on how the relations are present in the two tables.
You can also add the where clause to get only selected records.
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ToList();
}
来源:https://stackoverflow.com/questions/54187848/get-list-of-entity-models-in-dbcontext-entity-framework-core-2-1