使用链接的实体中的特定字段构建lambda表达式树

问题描述 投票:0回答:1

数据模型

public class TABLE
    {
        [Key]
        public int ID { get; set; }
        public int ONEFIELD { get; set; }

        // -------------------- ForeignKey --------------------
        [ForeignKey("People")]
        public long PeopleID { get; set; }
        public virtual People People { get; set; }
    }

    public class People
    {
        [Key]
        public long PeopleID { get; set; }
        public int CountryID { get; set; }
    }

我需要构建一个lambda来查询此MODEL:

获取TABLE.ONEFIELD = 1和TABLE.PEOPLE.COUNTRYID = 6

相当于LINQ

_context.TABLEs
  .Where(e => e.ONEFIELD == 1)
  .Include(e => e.People)
  .Where(i=>i.People.CountryID == 6);

我的尝试

  public static Expression<Func<TEntity, bool>> BuildLambda<TEntity>(OBJTYPE obj)
        {

        var item = Expression.Parameter(typeof(TEntity), "table");
        Expression query = null;


        // 1
        var prop1 = Expression.Property(item, "ONEFIELD");
        var value1 = Expression.Constant(1);
        var equal1 = Expression.Equal(prop1, value1);
        var lambdaFIELDONE = Expression.Lambda<Func<TEntity, bool>>(equal1, item);
        query = lambdaFIELDONE.Body;

        // 2
        var prop2 = Expression.Property(item, typeof(People).Name + ".CountryID");
        var value2 = Expression.Constant(6);
        var equal2 = Expression.Equal(prop2, value2);
        var lambdaCOUNTRYID = Expression.Lambda<Func<TEntity, bool>>(equal2, item);
        query = Expression.And(query, lambdaCOUNTRYID);

    }

但我收到此错误

System.ArgumentException:未为类型'SOLUTION.Models.TABLE'定义实例属性'People.CountryID'

我不需要泛型,只需一个固定的lambda(而且我不能使用LINQ)。

我尝试了几种方法来捕获People.CountryID,例如

Expression.Property(item1, typeof(People).GetProperty("CountryID"));
Expression.Property(item, typeof(People).Name+"." + typeof(People).GetProperty("CountryID"));
Expression.Property(item, typeof(People).Name + "." + typeof(People).GetProperties().Where(x => x.Name == "CountryID").FirstOrDefault().Name);

没有成功

任何想法?感谢

c# linq lambda expression expression-trees
1个回答
0
投票

因此,要构建嵌套的属性访问,必须嵌套访问每个级别的Expression。然后,您可以将测试合并为主体,并最终为结果创建lambda:

© www.soinside.com 2019 - 2024. All rights reserved.