[英]Dynamically loading DbSet to DbContext
How do I dynamically load into an EF7 DbContext
a X number of classes without explicitly writing them in a DbContext
class ?如何将 X 个类动态加载到 EF7
DbContext
,而无需在DbContext
类中显式编写它们?
For example, I tried to avoid it like this:例如,我试图像这样避免它:
public class MyDbContextClass : DbContext
{
public DbSet<Category> categories {get;set;}
public DbSet<Product> products {get;set;}
...
}
So it could be great to load Category and Product dynamically (without knowing if I have 2 or 20 classes).因此,动态加载 Category 和 Product 可能会很棒(不知道我是否有 2 个或 20 个类)。
Is it possible?有可能吗?
dbContext.Set<T>()
creates an instance of DbSet<T>
as long as T
is a type in your model (ie you have to add the entity type in OnModelCreating
). dbContext.Set<T>()
创建的实例DbSet<T>
只要T
是在模型的类型(即你必须添加的实体类型OnModelCreating
)。
See the source code for .Set<T>
.请参阅
.Set<T>
的源代码。
You should use this method:你应该使用这个方法:
All entities must inherit from BaseType...所有实体都必须从 BaseType 继承...
public static void RegisterAllEntities<BaseType>(this ModelBuilder modelBuilder, params Assembly[] assemblies) { var types = assemblies.SelectMany(a => a.GetExportedTypes()) .Where(c => c.IsClass && !c.IsAbstract && c.IsPublic && typeof(BaseType).IsAssignableFrom(c)); foreach (var type in types) modelBuilder.Entity(type); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.