将Linq查询转换为表达式树

时间:2018-11-17 13:19:34

标签: c# linq .net-core

我有一个lambda表达式:

query = query.Include(e => e.Product);

如何通过表达式树表示e => e.Product,以便可以在运行时动态创建它?

2 个答案:

答案 0 :(得分:1)

您可以动态创建这样的表达式:

// Declare input parameter of dynamically generated lambda expression
var parameterExpr = Expression.Parameter(typeof(e), "e");

// Select desired navigation property that should be included in a query result
var propertyExpr = Expression.Property(parameterExpr, "Product");

// Generate expression to cast value of this property to type Object. This is
// not strictly needed (if you know type of included property at compile-time).
var convertExpr = Expression.Convert(propertyExpr, typeof(Object));

// Create lambda expression. Thanks to previous "Expression.Convert",
// we can cast lambda to Expression<Func<e, Object>> instead of 
// Expression<Func<e, Product>> (because since you want to create expression
// dynamically, type of Product property is not necesarilly known at compile-time)
var lambdaExpr = (Expression<Func<e, Object>>)Expression.Lambda(convertExpr, parameterExpr);

// Use generated expression in a query
query = query.Include(lambdaExpr);

BTW:EF Core(可能还有EF6,但我没有经验)具有将属性名称作为参数的.Include()方法的重载,所以您实际上根本不需要生成表达式树:

query = query.Include("Product");

答案 1 :(得分:0)

由于您没有提供自己的类型,因此我创建了自己的类型,因此您的表情看起来会有所不同。

using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;

namespace ConsoleApp2
{
    class Product
    {

    }

    class Shop
    {

    }

    class SomeEntity
    {
        public Product Product { get; set; }
        public Shop Shop { get; set; }
    }

    class MyDbContext : DbContext
    {
        public DbSet<SomeEntity> Entities { get; set; }
    }

    class Program
    {
        private static Expression<Func<SomeEntity, Object>> GetExpression()
        {
            // a stupid random strategy
            if (DateTime.Now.Ticks % 2 == 0)
            {
                Expression<Func<SomeEntity, Object>> expression = e => e.Shop;
                return expression;
            }
            else
            {
                Expression<Func<SomeEntity, Object>> expression = e => e.Product;
                return expression;
            }
        }

        static void Main(string[] args)
        {
            var dbContext = new MyDbContext();

            IQueryable<SomeEntity> query = dbContext.Entities;

            var expression = GetExpression();

            query = query.Include(expression);
        }
    }
}