在VS调试窗口输出EF生成的SQL

     dbcontext.Database.Log = sql => { HandleSqlLog(sql);  };


     private void HandleSqlLog(string sql)
        {
            if (string.IsNullOrEmpty(sql)) return;
            sqlLog.Add(sql);
            if (sql.Contains("Closed"))
            {
                var sqlStr = sqlLog.FirstOrDefault(x => x.Contains("SELECT") ||x.Contains("UPDATE") || x.Contains("INSERT") || x.Contains("DELETE"));
                var sqlParms = sqlLog.Where(x => x.Contains("-- p__linq")).Select(x=> "@"+x.Replace("-- ",""));

                foreach (var item in sqlParms)
                {
                    var name = Regex.Match(item, @"@(.*?)[0-9]").Value;
                    var val = Regex.Match(item, @"'(.*?)'").Value;
                    sqlStr = sqlStr.Replace(name, val);
                }
                Trace.WriteLine("--------------------------------");
                Trace.WriteLine(sqlStr);
                Trace.WriteLine("--------------------------------");
                sqlLog.Clear();
            }
        }

 

posted @ 2022-03-25 14:40  Vince666  阅读(436)  评论(0编辑  收藏  举报