0

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.

0

1 Answer 1

1

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.

3
  • Thanks. A couple of things: 1) Does this go inside the class with the table definition? 2) I am getting a 'get or set accessor required' error on the 'Type myType' definition.
    – segnosaur
    Commented Feb 25, 2014 at 19:39
  • If I were doing this myself, I'd probably write it as an extension method on Object. See my update. Commented Feb 25, 2014 at 20:23
  • Thanks. I was able to get your first solution to work; I'll try to second value too, although I know I have at least one solution that works.
    – segnosaur
    Commented Feb 25, 2014 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.