0

I'm using EF6 and I'm looking for a solution to build a query that should select one of the fields in depends on a value that Expression returns. I'm playing with the LINQKit library for that but get a failure with this.

So I've created the reusable predicate that calculates logic in DB:

public partial class Study
{
    public static Expression<Func<Study, bool>> ShouldNameBeDisplayedForStaffExpression(int staffId)
    {
        return study =>
            (study.StudyViewAccessId == 1 && study.StudyEditAccessId == 1)
            || study.Roles.Any(y => y.StaffId == staffId);
        //Here other additional logic
    }
}

And now I need to set up proper value to Name field depends on the result that the predicate returns. The main requirement - it should be done on the query level (in IQueryable collection). The studiesCoreModelsQuery is EF6 EntitySets.

IQueryable<Study> studiesCoreModelsQuery = this._dbContext.Studies;
IQueryable<StudyViewModel> query = studiesCoreModelsQuery.AsExpandable().Select(x => new StudyViewModel
{
    Name = Study.ShouldNameBeDisplayedForStaffExpression(staffId).Invoke(x)
        ? x.Name
        : "Hidden"
});

Cannot understand how to get a result of Expression execution in Select. I will be appreciated for any help.

Ruslan Borovok
  • 520
  • 2
  • 17
  • Where is `staffId` coming from? Can you move `Study.ShouldNameBeDisplayedForStaffExpression(staffId)` call outside `Select`? Because where it is now it isn't really called. e.g. `var showNameExpr = Study.ShouldNameBeDisplayedForStaffExpression(staffId); ` and then inside `Select` do `Name = showNameExpr.Invoke(x) ? x.Name : "Hidden"` – Ivan Stoev Jan 21 '20 at 16:45
  • @IvanStoev The main idea to get an opportunity to reuse logic from the ShouldNameBeDisplayedForStaffExpression expression in other queries. That logic can not be executed outside of the query since it's a part of the query and should be applied to each element based on values in DB. staffId is a variable that's defined above the query - it can be any integer – Ruslan Borovok Jan 21 '20 at 16:58
  • 1
    That's what I'm saying. Obtain the expression outside the query and `Invoke` it inside. – Ivan Stoev Jan 21 '20 at 17:01

1 Answers1

1

@Ivan Stoev you are right.Your suggestion solved the issue. Work code next:

IQueryable<Study> studiesCoreModelsQuery = this._dbContext.Studies;
var expression = Study.ShouldNameBeDisplayedForStaffExpression(staffId);
IQueryable<StudyViewModel> query = studiesCoreModelsQuery.AsExpandable().Select(x => new StudyViewModel
{
    Name = expression.Invoke(x)
        ? x.Name
        : "Hidden"
});
Ruslan Borovok
  • 520
  • 2
  • 17