取得 Entity Framework 中 DbContext中所有的表名或类名

要取得 Conext 中相关的表的信息, 然后在 ContextManger中管理多个 context ,通过 IRespontry《Entity》根据 类型再自动选择 Conext,

从网上看到一个这样的方法:

var entities = (context as IObjectContextAdapter).ObjectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.CSpace);

            

            //跳过
            entities.ForEach(entity =>
            {
                if ("sysdiagrams" == entity.Name)
                    return;
                
                _objectContextTypeCache.Add(entity.FullName.ToLower(), key);
            });
 
上面的方法看起来不错,但会一个问题那就是如果两个上下文中存在同名的表,那就在字典中插入的时候会现异常,那怎么办呢?
我一度打算放弃,或者是在建立数据库的时候保证数据库的名称不同? 这样方法,有点扯的意思,不好。
 
然后经过思考,决定使用下面的方法 , DbContext 中 DbSet<>类型的变量, 其中的泛型其实就是我们要找的。

DB Conext类

 public class testContext : DbContext
    {
        static testContext()
        {
            Database.SetInitializer<testContext>(null);
        }

        public testContext()
            : base("Name=testContext")
        {
        }

        public DbSet<BlogPost> BlogPosts { get; set; }
        public DbSet<sysdiagram> sysdiagrams { get; set; }
        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new BlogPostMap());
            modelBuilder.Configurations.Add(new sysdiagramMap());
            modelBuilder.Configurations.Add(new UserMap());
        }
    }
 
 
所以根据上面的Context中的信息, 我做了一个方法 
 
   1:    /// <summary>
   2:          /// 取得dbcontext中的 DbSet 中的类型,Added by zbw911  
   3:          /// 2012-12-22
   4:          /// </summary>
   5:          /// <param name="context"></param>
   6:          /// <returns></returns>
   7:          private Type[] GetDbContextGetGenericType(DbContext context)
   8:          {
   9:   
  10:              var listtype = new List<Type>();
  11:              var type = context.GetType();
  12:   
  13:              var listpropertyies = type.GetProperties();
  14:   
  15:              foreach (var property in listpropertyies)
  16:              {
  17:                  var t = property.PropertyType;
  18:                  if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(DbSet<>))
  19:                  {
  20:                      var args = t.GetGenericArguments();
  21:                      listtype.AddRange(args);
  22:                  }
  23:              }
  24:   
  25:              return listtype.ToArray();
  26:          }

当然, 上面的方法返回值 应该用 list<type>类型,

大概意思到了就行了,不纠结了。

原文地址:https://www.cnblogs.com/zbw911/p/2829144.html