DbContext运行时动态附加上一个dbset

参考
Creating DbSet Properties Dynamically

C# code ?
1
DbSet<MyEntity>  set  = context.Set<MyEntity>();


C# code ?
1
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.
C# code ?

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);
         }
     }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值