Evgeny Evgeny - 8 months ago 45
C# Question

Create Expression<Func<T,K>> in .Net Runtime

there exists a nice database called LiteDB. What I find inconvenient there is an absence of attributes for specifying relation type (value/reference) between collections, but it provides fluent interface for that purpose (details: https://github.com/mbdavid/LiteDB/wiki/DbRef). I am lazy guy and don't want always synchronize this fluent relation description to follow the changes in my data model. So, I decided to realize runtime discovery of the data model entities with properties marked by attribute DbRef (my custom attribute). Unfortunately, I am stuck a little with creating the


in the .Net runtime... for providing it in the following call (first parameter):

BsonMapper.Global.Entity<Order>().DbRef(x => x.Customer, "customers");

Types T and K are given in runtime (here in example: T - Order, K - Customer).

I'll really appreciate if you guys give me some C# snapshot on how to create


in .Net runtime in order to provide it to ...DbRef(...) function.


Well, you have the entity type T, property type K and the property name. To build the Expression<Func<T, K>> you could simply use Expression.Parameter, Expression.Property and Expression.Lambda methods like this:

var parameter = Expression.Parameter(typeof(T), "x");
var body = Expression.Property(parameter, propertyName);
var selector = Expression.Lambda<Func<T, K>>(body, parameter);