62,233
社区成员




public class DefaultDBContext :DBContext{
public DbSet<User> User {get;set;}
..........
}
需要动态增加类似这个user的entity我现在只知道它的type的string;想用dbcontext读取这个未知实体的数据,有什么思路吗
DbSet<MyEntity> set = context.Set<MyEntity>();
或
DbSet set = context.Set( typeof( MyEntity ) );
或者利用反射,通过实现DbContext的OnModelCreating方法,参考
Dynamically Adding DbSet Properties in DbContext for Entity Framework Code First
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);
}
}