在 EntityFramework Core 使用動態欄位查詢
在之前 Dapper 的範例中,有提到如何動態將要查詢的欄位塞進 SQL 字串,也由於 Dapper 是用純 SQL 語法,所以只要組合一下查詢字串就可以了,但在 Entity Framework Core 中,顯然是沒辦法做到。幸好有 Dynamic LINQ 這個函式庫。
以下連結為本篇文章的範例位置:
其實用法非常的簡單,安裝完 Dynamic LINQ 後,就只要把字串丟進 Select 函式就好,程式碼如下:
public IQueryable<T> Query(string col = "*")
{
if (col == "*")
{
return _currentDbContext.Set<T>().AsNoTracking();
}
return _currentDbContext.Set<T>().AsNoTracking().Select<T>($"new \{\{ {col} \}\}");
//"new { City, CompanyName }"
}
其它的 LINQ function 也可以套用類似的做法。
參考資料