[英]How to select a value in LINQ Query in depends on Expression result?
我正在使用 EF6,我正在尋找一種解決方案來構建一個查詢,該查詢應該根據 Expression 返回的值選擇其中一個字段。 我正在為此使用 LINQKit 庫,但失敗了。
所以我創建了在 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
}
}
現在我需要根據謂詞返回的結果為 Name 字段設置適當的值。 主要要求 - 它應該在查詢級別(在 IQueryable 集合中)完成。 studyCoreModelsQuery 是 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"
});
無法理解如何在 Select 中獲得表達式執行的結果。 我將不勝感激任何幫助。
@Ivan Stoev 你是對的。你的建議解決了這個問題。 接下來的工作代碼:
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"
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.