我正在尝试使用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>
}
}
请检查代码中的注释。
谢谢!
答案 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();