How does Fluent NHibernate manage to get a reference to a property using that weird delegates?
For instance, if I want to map property Title I use:
> Map(x => x.Title);
That's weird because this delegate is only returning开发者_StackOverflow社区 the value of the property and not the property itself while NHibernate needs to know the property itself.
How does it work?
Map is a function, that (among other things via overloads) takes a Expression<Func<T>>
- i.e. it looks like a Func<T>
, but Expression<Func<T>>
gets converted into an expression tree instead of just the lambda.
Expression trees are basically ASTs, and you can write code to traverse an expression tree to extract a string with the property name, allowing you to reflect "normally" from then on.
There's a lot of stuff available where people write stuff that reflect on expression trees. Check out this post for example, for a demonstration on how to write a couple of utility methods to make the reflection easy.
精彩评论