Create Expression> in .Net Runtime

2019-09-11 00:56发布

问题:

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

Expression<Func<T,K>> 

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 as instances of System.Type (here in example: T - Order, K - Customer).

I'll really appreciate if you guys give me some hints on how to instantiate

Expression<Func<T,K>> 

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

回答1:

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(body, parameter);


回答2:

From you question. Let me send a screenshot to you maybe it can give you a clueExpression> Example

public IEnumerable<TEntity> Fetch(Expression<Func<TEntity, bool>>  predicate, Func<IQueryable<TEntity>,
        IOrderedQueryable<TEntity>> orderBy =null, int? page = null, int? pageSize = null)
    {
        IQueryable<TEntity> query = _dbSet;

        if (orderBy != null)
        {
            query = orderBy(query);
        }
        if (predicate != null)
        {
            query = query.AsExpandable().Where(predicate);
        }
        if (page != null && pageSize != null)
        {
            query = query.Skip((page.Value - 1) * pageSize.Value).Take(pageSize.Value);
        }
        return query;
    }

I hope this will help