c# - 如何编写动态 Lambda 表达式来访问第 N 个父实体?

标签 c# linq nhibernate lambda

我有一个应用程序使用 nhibernate 和 linq 对数据库进行查询。一切正常,但我映射了以下模型(与自动相关):

public class A
{
    public virtual int Id { get; set; } 
    public virtual A ParentA { get; set; }  
}

我有一个方法来处理一些信息,这个方法有一个 count 整数参数。 我想知道是否有任何方法可以访问 count 次 ParentA 属性来创建过滤器。

protected void Proccess(int count, int id)
{
    var query = session.Query<A>();

    // I would like to access, the number of count variable in parentA property, something like:
    // for sample: if count is 3, I would like a query like: 
    query.Where(x => x.ParentA.ParentA.ParentA.Id == id);

    // maybe something like this:
    for (int i = 0; i < count; i++)
    {
        query.Where(x => x.ParentA.ParentA.ParentA.Id == id);   
    }

    var result = query.ToList();

    // continue method...
}

有什么方法可以创建这种 Lambda 表达式吗?

最佳答案

像这样的东西应该可以工作:

protected void Process(int count, int id)
{
    var query = session.Query<A>().Where(BuildFilter(count,id));
    var result = query.ToList();
}

private static Expression<Func<A, bool>> BuildFilter(int count, int id)
{
   var x = Expression.Parameter(typeof(A), "x");

   Expression instance = x;
   if (count != 0)
   {
      var prop = typeof(A).GetProperty("ParentA");
      while (count > 0)
      {
         instance = Expression.Property(instance, prop);
         count--;
      }
   }

   var instanceId = Expression.Property(instance, "Id");
   var compareId = Expression.Constant(id);
   var body = Expression.Equal(instanceId, compareId);

   return Expression.Lambda<Func<A, bool>>(body, x);
}

关于c# - 如何编写动态 Lambda 表达式来访问第 N 个父实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16924791/

相关文章:

c# - jQuery 中的 ConfigurationManager.AppSettings

c# - Linq 查询获取对象列表并为每个对象获取另一个嵌套列表

c# - 首先按字母值对列表排序,然后按数值排序

c# - VB.NET 相当于 C# var 关键字

c# - windows phone 8.1 如何制作确定的圆形进度条

c# - 从 ASP.NET Core 2 Controller 返回 PDF

c# - 如何动态构建 () => x.prop lambda 表达式?

sql-server-2005 - NHibernate, SQL Server - 枚举到 int 的映射

c# - NHibernate 不支持指定的方法

c# - 二进制文件生成性能