entity 如何为dbcontext运行时动态附加上一个dbset

gispk47 2014-08-07 05:53:30
类似这样

public class DefaultDBContext :DBContext{
public DbSet<User> User {get;set;}
..........
}
需要动态增加类似这个user的entity我现在只知道它的type的string;想用dbcontext读取这个未知实体的数据,有什么思路吗
...全文
564 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
save4me 2014-08-08
  • 打赏
  • 举报
回复
参考 Creating DbSet Properties Dynamically

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
引用
However, for a project with even a fair bit of domain complexity, defining DbSet properties for all entities would not be possible and we need a way to dynamically read our Entity Types and add them dynamically in the DbContext. This can be achieved by implementing OnModelCreating method of the DbContext. The Entity Types can be read from either the executing assembly Assembly.GetExecutingAssembly() or by loading more than one assemblies which can be placed in a configuration file (as shown below in the example). For details about setting up the custom configuration section with your assemblies see my last post The following code will add all Class Types to the DbContext for all the assemblies added in the configuration file, notice we are actually calling modelBuilder.Entity<T>() method through reflection.

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);
        }
    }

62,233

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧