Я пытаюсь написать динамический запрос, используя Expression Tree. Мы имеем следующие объекты в нашей схеме:Как написать этот запрос linq динамически C#
- арендаторах
- Сотрудник
- Услуги
Там является 1 ко многим отношений между арендатором и Serivces и многие ко многим отношений между Сотрудник и 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>
}
}
Пожалуйста, проверьте комментарии в коде.
Спасибо!