Reputation: 530
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.
Upvotes: 0
Views: 292
Reputation: 530
@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"
});
Upvotes: 1