我对ObjectContext
内部不太熟悉,所以可能有一种更“原生”的方式,
...但是你需要一些东西reflection
来把你的财产拿出来。
(注意:我没有任何 db-first 方便检查,所以如果有一些错字你需要调整 - 应该可以)
public static object GetTableFromName(this TestDbContext db, string propertyName)
{
PropertyInfo property = null;
property = typeof(TestDbContext)
.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
return property.GetValue(db, null);
}
public static object GetTableFromType(this TestDbContext db, string tableTypeName)
{
// var tableType = typeof(TestDbContext).Assembly.GetType("YourNamespace.T_Members");
var tableType = Type.GetType(tableTypeName);
var genericType = typeof(ObjectSet<>).MakeGenericType(new[] { tableType });
var property = typeof(TestDbContext)
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => x.PropertyType == genericType).FirstOrDefault();
return property.GetValue(db, null);
}
并像使用它一样
var table = db.GetTableFromName("T_Members");
table = db.GetTableFromType("YourNamespace.T_Members);
// this gets you the `object` you'd still need to 'cast' or something