简体   繁体   中英

Entity Framework - access fields by number

I'm working with Entity Framework (v4) under Visual Studio 2010 (going against an Oracle database).

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:

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). 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.

Assuming MYTABLE_DEF is an ordinary Entity Class, you should be able to simply reflect over the public fields and return the nth one. 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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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