2016-08-01 71 views
1

我試圖在C#中使用實體框架構建一個動態查詢。最終目標是允許用戶在我的應用程序中構建自己的自定義查詢/報告。我從Angular和Typescript獲取這些信息,並且我的應用程序兩邊都有匹配的實體(前端和後端)。我的目標是建立一個sql查詢字符串,以後我可以直接在數據庫上執行。我目前不關心驗證,所以目前,格式錯誤的查詢是有效的結果(我將在稍後解決這個問題 - 一次一個步驟)。我的實體如下:動態查詢生成

public class AdHocLine 
    { 
     //The table that we are selecting a column from 
     [JsonProperty(PropertyName = "table")] 
     public string table; 
     //The column that a user wants to appear in their report 
     [JsonProperty(PropertyName = "column")] 
     public string column; 
     //Any filter criteria (e.g. 'equals abcd', this would be the 'abcd') 
     [JsonProperty(PropertyName = "userCriteria")] 
     public string userCriteria; 
     //The operator being used (e.g. 'equals abcd', this would be 'equals' 
     [JsonProperty(PropertyName = "op")] 
     public string op; 
     //If we are joining another column, this is the table we would be joining 
     [JsonProperty(PropertyName = "joinTable")] 
     public string joinTable; 
     //If we are joining another column, this is the column we would be joining 
     [JsonProperty(PropertyName = "joinColumn")] 
     public string joinColumn; 
     //Since this entity is meant to be delivered in an array, this is the array index 
     [JsonProperty(PropertyName = "index")] 
     public int index; 
     //This is the column from our current table that we are joining on 
     [JsonProperty(PropertyName = "joinWith")] 
     public string joinWith; 
    } 

有什麼,我缺少在我的實體,似乎明顯的?

在審閱相關問題後,用例可能會有幫助。假設我想從Project表中選擇ProjectName(一個字符串),並且希望從其父項ProgramElement(其中Project有一個指向ProgramElement的GUID,名爲ProgramElementId)中包含Description列。結果應該如下所示:

SELECT t1.ProjectName, t2.Description FROM Project as t1, ProgramElement as t2 <additional where clause information belongs here> 

在此先感謝!

+2

想我要指出的是,用戶確定的廣告-hoc查詢幾乎總是非常糟糕的主意。基本上,您的用戶可以通過形式不佳的查詢來使系統崩潰。事先確定需要什麼以及使用參數化存儲過程或「預先存儲的」查詢來訪問數據是一個更爲安全的選擇。雖然需要更多時間和深思熟慮,但「罐裝」報告要安全得多,而且幾乎總是比臨時性更高。話雖如此,我沒有看到你的課堂上有什麼明顯的缺失。 – Kevin

+0

謝謝!我允許AdHoc查詢的唯一原因是因爲它是在我的需求文檔中指定的,這是客戶特別要求的。客戶習慣於擁有直接的數據庫訪問權限,所以我試圖削減這個選擇和報告生成。由於我們仍然處於預發佈階段,因此如果它仍然有點粗糙或緩慢就沒關係。這些是我們以後可以清理的東西。不過,你說得好一點,我可能會與我的團隊主管談論如何試圖說服客戶說'Canned'報告可能會更好。 –

+0

@AndrewM。你到底在問什麼?如果不知道您的結果查詢的詳細程度如何,我們無法告訴您是否缺少某些內容。他們需要能夠離開,正確,交叉連接嗎? Applys?調用函數或存儲過程?聲明變量?創建臨時表?使用'CASE'語句?因爲目前所有這些都缺乏。 – iamdave

回答

1

我已經實現的東西有點比這更復雜的從SQL服務器端,如果你一定要我的第一個忠告是不要

但是......

明顯的遺漏是某種方式指定的JOIN類型

SELECT t1.ProjectName, t2.Description 
FROM Project as t1 
JOIN ProgramElement as t2 ON t2.joinColumn = t1.joinWith 
<additional where clause information belongs here> 

SELECT t1.ProjectName, t2.Description 
FROM Project as t1 
LEFT JOIN ProgramElement as t2 ON t2.joinColumn = t1.joinWith 
<additional where clause information belongs here> 

如果要包含一列而不是列屬性,那麼它是否更有意義?他們可能最終會要求多列,以便你可以做好準備。

對於這個問題你應該有列陣列從第二臺

但實際上它看起來像你需要踢回防的規格

+0

我和我的團隊領導交談過,看起來沒有辦法進行即席查詢。我會在不久的將來以多方向的方向前進,因爲我認爲它會更有用,也許更容易。第二個表中的列表示用戶想要加入的列,因此多列可能會出現問題。感謝您的建議,我可能會着眼於指定連接類型。 –