1 回答

TA貢獻1963條經驗 獲得超6個贊
返回的動態DbSet實際上只是真實DbSet對象的包裝器,您可以簡單地將其轉換為。然而,問題是,如果不使用泛型方法DbSet,就無法推斷出的類型。
以下方法可行,但可能是最不可取的:
private IEnumerable<T> GetDbSetByTableName<T>(string tableName)
{
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new ClearGUIEntities())
{
var dbset = prop?.GetValue(db);
return new List<T>(dbset as IEnumerable<T>);
}
}
現在,要解決這個問題,我們至少有兩個選擇:
DbSet
創建一個由所有s實現的接口(具有您需要的所有基本屬性) 。這樣,我們可以轉換動態對象,而無需在轉換時指定類型。返回一個
IEnumerable<dynamic>
可以即時施放的。
選項1
public interface IBaseProperties
{
int Id { get; set; }
string Name { get; set; }
}
public class MyTable : IBaseProperties
{
// Add these with either T4 templates or create partial class for each of these entities
public int Id { get; set; }
public string Name { get; set; }
}
private IEnumerable<IBaseProperties> GetDbSetByTableName(string tableName)
{
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new ClearGUIEntities())
{
var dbset = prop?.GetValue(db);
return new List<IBaseProperties>(dbset as IEnumerable<IBaseProperties>);
}
}
// ...
// Using it
// ...
var dynamicdbset = GetDbSetByTableName("MyTable");
int id = dynamicdbset.FirstOrDefault().Id;
選項 2
private IEnumerable<dynamic> GetDbSetByTableName(string tableName)
{
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new ClearGUIEntities())
{
var dbset = prop?.GetValue(db);
return new List<dynamic>(dbset as IEnumerable<dynamic>);
}
}
// ...
// At this point, you can basically access any property of this entity
// at the cost of type-safety
string id = dynamicdbset.FirstOrDefault().Id;
string name = dynamicdbset.FirstOrDefault().Name;
順便說一句,強制轉換List<T>是必要的,因為您使用的是using塊之外的對象,此時它將被處置。
new List<IBaseProperties>(dbset as IEnumerable<IBaseProperties>);
- 1 回答
- 0 關注
- 164 瀏覽
添加回答
舉報