這個問題在這里已經有了答案: 使用反射從字串中獲取屬性值 23 個答案 6 小時前關閉。
我想為 LINQ 串列宣告類屬性的變數。我在資料庫中有大約 100 個屬性,我想根據用戶選擇更改輸出資料。例如,如果用戶選擇“A”,我想從 EntityFramework 獲取“A”值。
這是我的示例代碼:
List<ReadTime> report = bWDiagnosticEntities2.CA190STEST
.Where(x => (x.Date > StartDate) && (x.Date <= EndDate))
.Select(x => new ReadTime
{
Date = x.Date,
kody5 = x.kodyBledow5NetVarA
})
.OrderBy(x => x.Date)
.ToList();
我想改變:
kody5 = x.kodyBledow5NetVarA
到
kody5 = myVariable
其中 myVariable 取決于用戶發送的模型。
uj5u.com熱心網友回復:
我認為最簡單的方法是拆分查詢和投影部分。查詢將由 EF 在資料庫端運行,并檢索所有欄位。
然后您在記憶體中進行投影,并根據用戶的選擇注入屬性(用戶需要從串列中選擇現有屬性)。
在 EF 查詢中要記住的一件重要事情是,當您呼叫 時ToList(),您將執行實際的資料庫查詢。然后所有進一步的陳述句將在記憶體中執行。
// This will perform an EF query, filtered by the where predicate
var reportEntities = yourContext.YourEntityModelDbSet
// save resources on EF context if you don't need to update entities later
.AsNoTracking()
// Filter as much as you can in this predicate, for it will
// be translated into SQL by EF
.Where(x => x.Date > StartDate && x.Date <= EndDate)
// Calling ToList will retrieve all entites matching the where predicate
// including all their fields (take care of data size)
.ToList();
// Then, use reflection to retrieve the data
// according to user's choice
var userChoice = GetUserInput(); // will return the property name as a string
var report = reportEntities
.Select(x => new ReadTime
{
Date = x.Date,
// Using reflection to get the value of a property
// Given its name.
Kody5 = x.GetType().GetProperty(userChoice)?.GetValue(x, null)
})
.ToList();
由于
?.不存在的屬性選擇,操作員會吞下任何例外。它保證您不會遇到運行時例外,但您永遠不會知道屬性選擇是否錯誤。
如果資料量是一個問題(并且可能,因為您告訴過您有一百個欄位),請在Select()之前執行第一個ToList(),在任何情況下,您將嚴格只投影您需要的欄位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/453506.html
標籤:C# asp.net-mvc 实体框架 林克
下一篇:ASP.NETCoreMVC前端開發ListshowView不斷獲取System.Collections.Generic.List
