参考
Creating DbSet Properties Dynamically
1
|
DbSet<MyEntity>
set
= context.Set<MyEntity>();
|
或
1
|
DbSet
set
= context.Set(
typeof
( MyEntity ) );
|
或者利用反射,通过实现DbContext的OnModelCreating方法,参考
Dynamically Adding DbSet Properties in DbContext for Entity Framework Code First
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public
class
MyAppContext : DbContext
{
protected
override
void
OnModelCreating(DbModelBuilder modelBuilder)
{
CustomAssemblySection configSection = (CustomAssemblySection)System.Configuration.ConfigurationManager.GetSection(
"CustomAssemblySection"
);
foreach
(CustomAssembly customAssembly
in
configSection.Assemblies)
{
Assembly assembly = Assembly.Load(customAssembly.Name);
foreach
(Type type
in
assembly.ExportedTypes)
{
if
(type.IsClass)
{
MethodInfo method = modelBuilder.GetType().GetMethod(
"Entity"
);
method = method.MakeGenericMethod(
new
Type[] { type });
method.Invoke(modelBuilder,
null
);
}
}
}
base
.OnModelCreating(modelBuilder);
}
}
|