简体   繁体   English

实体框架-按数字访问字段

[英]Entity Framework - access fields by number

I'm working with Entity Framework (v4) under Visual Studio 2010 (going against an Oracle database). 我正在Visual Studio 2010下使用Entity Framework(v4)(针对Oracle数据库)。

A record has been read in as follows: 已读取一条记录,如下所示:

MYTABLE_DEF t;
t = db.MYTABLE_DEF.Find(identifier);

Now, I know I can access the fields in t directly: 现在,我知道可以直接访问t中的字段:

Console.WriteLine(t.SOMEVALUE);

What I would like to be able to do is reference the fields in t, either by doing some sort of 'index' (something like t[0] for first field, t[1] for second field). 我想做的是通过执行某种“索引”来引用t中的字段(类似于第一个字段的t [0],第二个字段的t [1])。 If that's not possible, then is it possible to bind the field at run time? 如果不可能,那么是否可以在运行时绑定字段? Something like: 就像是:

 string whichfield = Console.ReadLine();
 Console.WriteLine(t[whichfield])      // I know this won't work

I've basically been learning Entity Framework through trial and error (and google) but haven't come across anything sort of indirect reference like that. 我基本上是通过反复试验(和Google)来学习Entity Framework,但是还没有遇到像这样的任何间接引用。

Assuming MYTABLE_DEF is an ordinary Entity Class, you should be able to simply reflect over the public fields and return the nth one. 假设MYTABLE_DEF是一个普通的Entity Class,您应该能够简单地反映公共字段并返回第n个。 Something like this: (untested) 像这样:(未经测试)

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;
}

For convenience, I would write this as an extension method on object : 为了方便起见,我将其写为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];
}

which you can then call thusly: 然后可以这样调用:

var theSixthProperty = myObject.IndexedProperty(6);
var valueOfSixthProperty = theSixthProperty.GetValue();

Having it as an Extension Method eliminates the problem of having to write an indexer for every Entity Class. 将其用作扩展方法消除了必须为每个实体类编写索引器的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM