How do I view the SQL generated by the Entity Framework?

后端 未结 22 3340
别那么骄傲
别那么骄傲 2020-11-21 05:35

How do I view the SQL generated by entity framework ?

(In my particular case I\'m using the mysql provider - if it matters)

22条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 06:14

    Entity Framework 4 Solution

    Most of the answers here were EF6-specific. Here's one for those of you still using EF4.

    This method replaces the @p__linq__0/etc. parameters with their actual values, so you can just copy and paste the output into SSMS and run it or debug it.

        /// 
        /// Temporary debug function that spits out the actual SQL query LINQ is generating (with parameters)
        /// 
        /// IQueryable object
        private string Debug_GetSQLFromIQueryable(IQueryable q)
        {
            System.Data.Objects.ObjectQuery oq = (System.Data.Objects.ObjectQuery)q;
            var result = oq.ToTraceString();
            List paramNames = new List();
            List paramVals = new List();
            foreach (var parameter in oq.Parameters)
            {
                paramNames.Add(parameter.Name);
                paramVals.Add(parameter.Value == null ? "NULL" : ("'" + parameter.Value.ToString() + "'"));
            }
            //replace params in reverse order, otherwise @p__linq__1 incorrectly replaces @p__linq__10 for instance
            for (var i = paramNames.Count - 1; i >= 0; i--)
            {
                result = result.Replace("@" + paramNames[i], paramVals[i]);
            }
            return result;
        }
    

提交回复
热议问题