# 在 VisualStudio 使用 Debug 視窗偵錯及利用 Database.log 取得 Entity Framework 轉換後的 SQL 語法 ###### tags: `程式設計` 在檢查程式邏輯的時候,常常需要執行後檢查變數目前的值 在Visual Studio有多種方式可以觀察變數,例如: * 設定中斷點後,游標直接移到變數上 * 將變數加入監看式 * Debug 視窗 * 將變數寫入檔案 這邊要提的是 Debug 視窗的使用方式,首先要先說 Debug 視窗的位置 檢視(V) > 輸出 (Ctrl+Alt+O) 在輸出視窗將下拉選單選到 "偵錯" 即可開啟 Debug 視窗   再來是 Debug 的使用方法,最基礎的用法就是在 Debug 視窗上寫入固定的字串和變數,範例如下 ```=C# using System.Diagnostics; //.... other code var a = 1; Debug.Write("Start"); Debug.WriteLine("變數a = " +a); Debug.Write("===End==="); ``` 其中 Write 是寫入但不換行 WriteLine 是寫入後會切換到下一行 需要變數和字串混用,則用 + 符號分隔 ## 取得 Entity Framework 轉換後的SQL語法 在使用 Entity Framework 時,若想觀察轉換後 SQL 語法,可以利用 Database.Log 的方式,將 SQL 語法寫入 Debug 視窗觀察 ```=C# using (Models.mjibwwwEntities1 db = new Models.mjibwwwEntities1()) { db.Database.Log = sql => Debug.Write(sql); var result = db.Custom.Where(s=>s.id == ID).FirstOrDefault(); // 執行到這邊時會在 debug 視窗顯示 sql語法 } ``` ## 參考文件 * 記錄和攔截資料庫作業 https://docs.microsoft.com/zh-tw/ef/ef6/fundamentals/logging-and-interception
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up