zoukankan      html  css  js  c++  java
  • 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);
            }
        }
  • 相关阅读:
    二线城市的创业人才之战
    小程序的风口到底如何?
    短视频广告一条上百万,揭秘短视频背后的故事
    让我们来看看这些企业的创始人,在互联网金融的十年里的故事
    背靠大树成为创业成功的显学
    草根站长的艰辛创业路
    互联网大佬们的创业重要选择时刻
    80后的罗敏已经在创业路上走了十几年
    CentOS7 通过 YUM 升级 VIM8
    matplotlib 画图中的basemap安装问题
  • 原文地址:https://www.cnblogs.com/jimcsharp/p/6005062.html
Copyright © 2011-2022 走看看