2012-03-21 70 views
0

我想建立一個控制器,爲我所有的查找表編輯請求。我有我的DbContext從IdNamePairBase派生,e.g幾個DbSet變量:如何以編程方式查詢DbContext中的DbSet?

public DbSet<Country> Countries { get; set; } // Country derives from IdNamePairBase 

如何傳遞的其中之一的名稱查詢,以獲得在該列表中的所有項目?例如。

var list = db.GetNamedDbSet("Countries"); 

然後,加分,我需要從list得到一個IEnumerable<IdNamePairBase>

回答

0

如果表的名稱與類型相對應,則可以在DbContext上使用Set(Type type)

public IEnumerable<IdNamePairBase> GetNamedDbSet(string dbSetName) 
{ 
     var property = Type.GetType(dbSetName); 
     if (property == null || !property.CanRead) 
     { 
     throw new ArgumentException("DbSet named " + dbSetName + " does not exist."); 
     } 

     // at this point you might want to check that the property is an enumerable type 
     // and that the generic definition is convertible to IdNamePairBase by 
     // inspecting the property type. If you're sure that these hold, you could 
     // omit the check. 

     return Set(type).Cast<IdNamePairBase>(); 
} 

原來的答案

如果集的名稱相匹配的屬性名稱,你可以使用反射。

public IEnumerable<IdNamePairBase> GetNamedDbSet(string dbSetName) 
{ 
     var property = this.GetType().GetProperty(dbSetName); 
     if (property == null || !property.CanRead) 
     { 
     throw new ArgumentException("DbSet named " + dbSetName + " does not exist."); 
     } 

     // at this point you might want to check that the property is an enumerable type 
     // and that the generic definition is convertible to IdNamePairBase by 
     // inspecting the property type. If you're sure that these hold, you could 
     // omit the check. 

     var result = new List<IdNamePairBase>(); 
     foreach (var item in (IEnumerable)property.GetValue(this, null)) 
     { 
      result.Add((IdNamePairBase)item); 
     } 
     return result; 
} 
+0

我從反射獲得屬性值,如您所示,謝謝,但我希望動態類型先投射到正確的DbSet 類型。我會很快更新這個問題。 – ProfK 2012-03-21 13:00:46

+0

@ProfK - 這比我想象的要複雜,因爲要獲得一個強類型(通用)方法到正確的DbSet,你必須知道類型。如果你知道類型,那麼你應該能夠簡單地使用適當的屬性。我懷疑一個非泛型DbSet是否可以輕鬆完成工作。 – tvanfosson 2012-03-21 14:11:59

+0

現在太複雜了。謝謝。 – ProfK 2012-03-21 14:41:30