如何动态编写这个linq查询c#

时间:2014-02-02 05:46:39

标签: c# linq

我正在尝试使用Expression Tree编写动态查询。我们的架构中有以下实体:

  • 租户
  • 员工
  • 服务

Tenant和Serivces之间存在 1 to many 关系,以及Employee和Serivces之间的多对多关系。租户和员工都包含ICollection of Services。

现在我必须动态编写以下查询:

  context.{EntityDbSetResolveAtRunTime out of Tenant OR Employee entity}
         .SingleOrDefault(p => 
          p.{PropertyResolveAtRunTime out of TenantId or EmployeeId} == id)
         .Services;

以下是我尝试过的代码:

public class ServiceRpository<TEntity> : where TEntity : class
{
    private DbSet<TEntity> dbset;

    public ServiceRepository(MyContext context)
    {
      dbset = context.Set<TEntity>();
    }

    public List<Services> Get(string id)  
    {
       //p 
       ParameterExpression predicateVariable = Expression.Parameter(typeof(TEntity), "p");
       //p => p.TenantId OR p => p.EmployeeId
       Expression left = Expression
               .Property(predicateVariable, typeof(TEntity)
               .GetProperty(typeof(TEntity).Name + "Id"));
       //id
       Expression rightConstant = Expression.Constant(id);
       //p => p.TenantId == id OR p => p.EmployeeId == id
       Expression predicateBody = Expression.Equal(left, rightConstant);

       // predicateBody variable contains 
       // p => p.TenantId == id OR p => p.EmployeeId == id

       //The below code will give us the Tenant Or Employee entity
       var entity = dbset.SingleOrDefault(Expression.Lambda<Func<TEntity, bool>>(
           predicateBody, new ParameterExpression[] { predicateVariable }));


       // Now the problem is how i get Serivces out of the entity, something like
       // entity.Services;
       // and what should be 
       // the return type of this function which orignally i want List<Services>

    }
} 

请检查代码中的注释。

谢谢!

1 个答案:

答案 0 :(得分:1)

我现在无法对它进行测试,但是后续工作应该有效(或者至少引导你走向正确的方向)。

向抓取服务添加Include次调用:

//The below code will give us the Tenant Or Employee entity
var entity = DbSet.Include("Services").SingleOrDefault(
    Expression.Lambda<Func<TEntity, bool>>(predicateBody, new ParameterExpression[] { predicateVariable }));

Services属性值设为IEnumerable<Service>并致电ToList()以确保返回List<Service>

return ((IEnumerable<Service>)typeof(TEntity).GetProperty("Services").GetValue(entity, null)).ToList();