我正在使用Visual Studio 2010下的实体框架(v4)(针对Oracle数据库)。
已读入记录如下:
MYTABLE_DEF t;
t = db.MYTABLE_DEF.Find(identifier);
现在,我知道我可以直接访问 t 中的字段:
Console.WriteLine(t.SOMEVALUE);
我希望能够做的是引用 t 中的字段,或者通过执行某种"索引"(例如 t[0] 表示第一个字段,t[1] 表示第二个字段)。如果这是不可能的,那么是否可以在运行时绑定字段?像这样:
string whichfield = Console.ReadLine();
Console.WriteLine(t[whichfield]) // I know this won't work
我基本上一直在通过反复试验(和谷歌)来学习实体框架,但没有遇到过这样的间接参考。
假设MYTABLE_DEF是一个普通的实体类,你应该能够简单地反映公共字段并返回第n个。 像这样的东西:(未经测试)
public object this[int index]
{
Type myType = this.GetType();
PropertyInfo[] myProperties =
myType.GetProperties(BindingFlags.Public|BindingFlags.Instance);
object result = myProperties[myIndex].GetValue(myClassInstance, null);
return result;
}
为方便起见,我会将其编写为object
上的扩展方法:
public static Property IndexedProperty(this object obj, int index)
{
Type myType = obj.GetType();
PropertyInfo[] myProperties =
myType.GetProperties(BindingFlags.Public|BindingFlags.Instance);
return myProperties[myIndex];
}
然后你可以这样调用:
var theSixthProperty = myObject.IndexedProperty(6);
var valueOfSixthProperty = theSixthProperty.GetValue();
将其作为扩展方法可消除必须为每个实体类编写索引器的问题。