2011-05-02 155 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(); 
相關問題