I want to invoke a method that expects a parameter like this:
Expression<Func<sometype, 'a>> expr
I need to construct this parameter at runtime, because I won't know what the anonymous type will look like before; it could have any amount of fields:
x => new { a=x.a, b=x.b, c=x.c, etc... }
I can create a type at runtime that has the same 'signature' (Is that the correct word for this?) as the desired anonymous type, but the question is: How do I construct this lambda expression at runtime from that? Especially Expression.New is bugging me, because I need to pass a constructorInfo to it that I have to get from an existing type (which can indeed be an anonymous type, but I can't create an anonymous type at runtime. Or is there a way to do that?).
Update (some context as requested in the comments)
The method I want to invoke is:
DependentNavigationPropertyConfiguration.HasForeignKey<TKey>(Expression<Func<TDependentEntityType, TKey>> foreignKeyExpression)
The reason I want to do this is to automatically make a navigation property to an entity that inherits from a certain base class include the key of that base class in the foreign key. Because an entity can have multiple key fields of any type, the type TKey is only known to me at runtime.
Use a separate method:
Note however, that the starting type (in my example
String
) must be known up front.Update:
Since what it sounds like you're trying to do is dynamically create a type, I'll give you a simple example of how to do that.
As you can see, this is a little more complicated. If you want to study the topic further though, definitely reference
Reflectoin.Emit
.you can do simply like this
Anonymous types are a compiler feature. If you don't get the compiler to create them at compile-time, then you will have to use meta-programming - either
TypeBuilder
or maybeCSharpCodeProvider
. You might be better off using tuples - at least they are easy to create (you can useTuple.Create
easily enough).As for the expression; I would suggest typing it as
Expression<Func<sometype, object>>
- which will work for any formulation. The code inspecting theExpression
can of course see what the actual type is.