Get List of Entity Models in DbContext Entity Framework Core 2.1

孤街醉人 提交于 2020-01-02 06:26:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!