LINQ and Reflection

  • Thread starter Thread starter wildThought
  • Start date Start date
W

wildThought

If I get an object generated by SQL Metal I can do a call like:

db.Persons.Add(new Person(){name = "ED"};

So far, so good. However, we are loading a DB from MetaData, I need
to do this via reflection.

If I do db.GetType().GetProperty("Persons")

No Problem. I get the right object.

Now, when I do
db.GetType().GetProperty("Persons").GetType().GetMethods()

The Add method is not reflected, I wanted to be able to Dynamically
Invoke this object, but it does not show up as avalid Method.

Any Thoughts?
 
wildThought said:
If I get an object generated by SQL Metal I can do a call like:

db.Persons.Add(new Person(){name = "ED"};

So far, so good. However, we are loading a DB from MetaData, I need
to do this via reflection.

If I do db.GetType().GetProperty("Persons")

No Problem. I get the right object.

Now, when I do
db.GetType().GetProperty("Persons").GetType().GetMethods()

The Add method is not reflected, I wanted to be able to Dynamically
Invoke this object, but it does not show up as avalid Method.

Any Thoughts?

Yes - GetProperty returns a PropertyInfo, and you're calling GetType()
on that. You should be using

db.GetType().GetProperty("Persons").PropertyType.GetMethods()
 
Jon Skeet said:
Yes - GetProperty returns a PropertyInfo, and you're calling GetType()
on that. You should be using

db.GetType().GetProperty("Persons").PropertyType.GetMethods()

Moreover, you likely want to use the override of GetMethods that accepts an
argument. From its doc page:

The following BindingFlags filter flags can be used to define which methods
to include in the search:

a.. You must specify either BindingFlags.Instance or BindingFlags.Static
in order to get a return.

b.. Specify BindingFlags.Public to include public methods in the search.

c.. Specify BindingFlags.NonPublic to include non-public methods (that is,
private and protected members) in the search.

d.. Specify BindingFlags.FlattenHierarchy to include public and protected
static members up the hierarchy; private static members in inherited classes
are not included.

The following BindingFlags modifier flags can be used to change how the
search works:

a.. BindingFlags.DeclaredOnly to search only the methods declared on the
Type, not methods that were simply inherited.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top