2011-05-02 68 views
0

的集合属性我有一个类MyDatabaseContext具有一系列DbSet集合属性:获取特定类型的

public DbSet<EntityA> EntitiesA { get; set; } 
public DbSet<EntityB> EntitiesB { get; set; } 
public DbSet<EntityC> EntitiesC { get; set; } 

我需要给实体类型的集合的名称。
例如,我有“EntityB”,并希望得到“EntitiesB”的结果。

因为MyDatabaseContext是自动生成的(T4模板),所以我真的很想避免switch-case语句。

+0

你为什么需要财产的名称? – 2011-05-02 18:21:30

+0

好点。即使在设计时,变量EntitiesC的类型'EntityC'也应该被广泛使用。 – ProfK 2013-03-10 11:05:15

回答

1

如果你只是希望你去的地方的财产的名称。我只会改进猎人给出的答案。您可以使用与返回类型相同的字符串方法。

public string GetEntitiName<T>() where T : class 
    { 
     PropertyInfo propInfo = typeof(MyDatabaseContext).GetProperties().Where(p => p.PropertyType == typeof(DbSet<T>)).FirstOrDefault(); 
     string propertyName = propInfo.Name; //The string has the property name .. 
     return propertyName;  
    } 

我尝试了一个与您的情况类似的示例。尝试用DbSet替换列表。

class Program 
    { 
     public static void GetEntities<T>() where T : class 
     { 

      var info = typeof(TestClass1).GetProperties().Where(p => p.PropertyType == typeof(List<T>)); 

      Console.WriteLine(info.FirstOrDefault().Name); 
     } 

     static void Main(string[] args) 
     { 
      GetEntities<int>(); 
      Console.ReadLine(); 
     } 
    } 
    public class TestClass1 
    { 
     public List<int> IntTest { get; set; } 
     public List<double> DoubleTest { get; set; } 
     public List<string> IStringTest { get; set; } 
    } 

此示例的工作原理。

+0

我在typeof上得到这个错误(DbSet ):类型'T'必须是一个引用类型,以便将它用作通用类型或方法'系统中的参数'TEntity' .Data.Entity.DbSet ' – 2011-05-02 18:25:30

+0

请尝试编辑后的解决方案 – gordanvij 2011-05-02 18:36:51

+0

如果要在泛型类型定义上使用typeof,您需要使用空<>来完成,如:typeof(字典<,>) – 2011-05-02 18:37:01

0

你生成的文件是一个局部类,你可以创建一个新的文件,并使用关键字partial声明具有相同名称的类,然后让这将返回所需收集的方法...

+0

但我不得不去切换案例路线,我真的想避免... – 2011-05-02 17:26:04

+0

我没有在这里看到其他选项......但你可以:1.在每个文件中使用一个上下文(多个edmx )。 2.让它产生一个'类'并拥有一个属性'DbSet '。对不起,如果这没有帮助... – BrunoLM 2011-05-02 17:30:59

0

我自己并没有真正做到这一点,但它听起来像你想要做的就是使用反射来找到具有适当的泛型类型参数的类型“DbSet”的属性。下面的伪C#应该让你开始:

foreach (FieldInfo field in this.GetType()) 
{ 
    if (field.FieldType.IsGenericType) 
    { 
    foreach (Type param in field.FieldType.GetGenericArguments()) 
    { 
     if (param.Name == soughtType) 
     { 
     return field.Name; 
     } 
    } 
    } 
} 
1

我知道这是旧的页面,但我的答案也许有用的其他人在这里提到。 (像我一样)

我想你想访问EntitiesB来运行它的查询,如EntitiesB.Where(a=>a.bla=="blabla")。如果我是正确的或本页面的另一个访问者需要这样的事情,只是很容易地使用下面的代码:

using System.Data.Entity.Infrastructure; 
using System.Data.Objects; 

((IObjectContextAdapter)_dbContext).ObjectContext.CreateObjectSet<EntityB>() 

说明:

_dbContext is Context class inherting from DbContext. 
EntitiesB is DbSet<EntityB> defined in Context class. 

例子:

Ilist result = ((IObjectContextAdapter)_dbContext).ObjectContext.CreateObjectSet<EntityB>().Where(b=>b.bla=="blabla").ToList();