我正在尋找一種方法來合併多個表達式樹以構建實體框架查詢的選擇器。查詢根據用戶提供的參數知道要選擇哪些列。例如,基本查詢返回實體的ID/Name列。如果顯式設置參數以檢索Description列,則查詢將返回ID/Name/Description。合併實體框架表達式樹
因此,我需要的代碼爲MergeExpressions方法在下面的代碼。
Expression<Func<T, TDto>> selector1 = x => new TDto
{
Id = x.Id,
Name = x.Name
}
Expression<Func<T, TDto>> selector2 = x => new TDto
{
Description = x.Description
}
var selector = selector1;
if (includeDescription)
selector = MergeExpressions(selector1, selector2);
var results = repo.All().Select(selector).ToList();
謝謝。
簡單而乾淨的解決方案。謝謝伊萬。 – Joe