1

我用

  `.....
   .....
  query = query.Where(criterion, fiedNames);
  string sql2 = ((ObjectQuery)query).ToTraceString();'

获取和调整将由 LINQ 执行的 SQL 代码。

当我快速观看时,我得到以下我不理解的 SQL 语句。

SELECT [UnionAll2].[C3] AS [C1], [UnionAll2].[C4] AS [C2],
[UnionAll2].[C5] AS [C3], [UnionAll2].[C6] AS [C4], 
[UnionAll2].[C7] AS [C5], 
[UnionAll2].[C8] AS [C6], 
[UnionAll2].[C9] AS [C7],  
..... few hundereds line more.....
@p__linq__4 AS [C2], 
.....
CASE 
     WHEN ( [Join5].[id] IS NULL ) THEN 
     Cast(NULL AS INT) 
     WHEN ( @p__linq__0 = 1 )

.......

显然,如果我粘贴到 SQL 管理工作室并执行它,如果我没有传递 ... 的值,它会抛出错误@p__linq__0

我的问题:如何获取可以在 SQL 管理上执行的跟踪 SQL?

4

4 回答 4

1

This extension method you can assert:

 /// <summary>
    /// Traces IQueryable's DB query />
    /// </summary>
    /// <typeparam name="TEntity">IQueryable type</typeparam>
    /// <param name="query">The IQueryable query</param>
    /// <returns>Query</returns>
    public static string ToTraceString<TEntity>(this IQueryable<TEntity> query)
    {
        StringBuilder sb = new StringBuilder();

        var objQuery = query as ObjectQuery<TEntity>;
        if (objQuery != null)
        {
            sb.AppendLine();
            if(objQuery.Parameters.Count > 0)
            {
                sb.AppendLine("Query parameters:");
                sb.AppendLine("--------------------------------------------------------------");
                sb.AppendLine("      Name          |        Type        |       Value        ");
                sb.AppendLine("--------------------------------------------------------------");
                foreach (var param in objQuery.Parameters) 
                {
                    sb.AppendFormat("{0, -20}|{1, -20}|{2, -20}{3}", param.Name, param.ParameterType.ToString(), param.Value, Environment.NewLine);
                }
                sb.AppendLine();
            }

            string partialQuery = objQuery.ToTraceString();
            objQuery.Parameters.ToList().ForEach(p => partialQuery = partialQuery.Replace(":" + p.Name, p.Value.ToString()));

            sb.AppendLine(partialQuery);
        }

        // replace 

        return sb.ToString();
    }
于 2013-10-30T12:17:21.157 回答
1
   public class LinqProvider<T>
    {
        static readonly FieldInfo INTERNAL_QUERY_FIELD;
        static readonly FieldInfo QUERYSTATE_FIELD;

        static LinqProvider()
        {
            INTERNAL_QUERY_FIELD = typeof(DbQuery<T>).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.Name.Equals("_internalQuery"));
            QUERYSTATE_FIELD = typeof(System.Data.Entity.Core.Objects.ObjectQuery<>).BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(x => x.Name == "_state");
        }

        public IQueryable<T> QueryContext { get; set; }

        InternalQuery _InternalQueryContext;
        public InternalQuery InternalQueryContext
        {
            get
            {
                if (_InternalQueryContext == null)
                {
                    _InternalQueryContext = new InternalQuery();

                    if (QueryContext is DbQuery<T>)
                    {
                        var internalQuery = INTERNAL_QUERY_FIELD.GetValue(QueryContext);

                        var objectQueryField = internalQuery.GetType().GetProperties().FirstOrDefault(f => f.Name.Equals("ObjectQuery"));

                        _InternalQueryContext.ObjectQueryContext = objectQueryField.GetValue(internalQuery) as System.Data.Entity.Core.Objects.ObjectQuery<T>;
                    }
                    else if (QueryContext is System.Data.Entity.Core.Objects.ObjectQuery<T>)
                    {
                        _InternalQueryContext.ObjectQueryContext = (QueryContext as System.Data.Entity.Core.Objects.ObjectQuery<T>);
                    }
                }

                return _InternalQueryContext;
            }
        }

        public LinqProvider(IQueryable<T> queryContext)
        {
            QueryContext = queryContext;
        }

        public class InternalQuery
        {
            public System.Data.Entity.Core.Objects.ObjectQuery<T> ObjectQueryContext { get; set; }

            public string ToTraceString(IDictionary<string, object> Parameters = null)
            {
                var state = QUERYSTATE_FIELD.GetValue(ObjectQueryContext);

                var mi = state.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(x => x.Name == "GetExecutionPlan");

                mi.Invoke(state, new object[] { null });

                var paramState = state.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(x => x.Name == "_parameters");

                if (paramState != null)
                {
                    System.Data.Entity.Core.Objects.ObjectParameterCollection col = paramState.GetValue(state) as System.Data.Entity.Core.Objects.ObjectParameterCollection;

                    if (col != null && Parameters != null)
                    {
                        foreach (var item in col)
                        {
                            Parameters.Add(item.Name, item.Value);
                        }
                    }
                }

                return ObjectQueryContext.ToTraceString();
            }
        }
    }
于 2014-06-24T15:21:44.583 回答
0

例如,将扩展方法名称更改为 TraceString2,因为 TraceString 是相同的 ObjectQuery 方法名称。

此扩展,显示查询参数的所有数据(@p_ linq _0 ...):

using (var context = new MyEntities(true))
{
    string cpty = "MiCpty";
    DateTime date = DateTime.Today;

    var query = context.CECA_SPECIAL_CAS.Where(a => a.IDACUERDO == cpty 
                                                    && a.FECHAENTRADA == date);
    query.ToList();

    System.Diagnostics.Debug.Print(query.ToTraceString2());
}

结果:

查询参数:

姓名 | 类型 | 价值

p_ linq _0 |System.String |MiCpty p_linq _1
| System.DateTime |31/10/2013 00:00:00

选择“Extent1”。“IDACUERDO”作为“IDACUERDO”,“Extent1”。“NOMBREPRINCIPAL”作为“NOMBREPRINCIPAL”,“Extent1”。“NOMBRELEGAL”作为“NOMBRELEGAL”,“Extent1”。“NOMBRELARGO”作为“NOMBRELARGO”,“范围 1"."FECHAENTRADA" 作为 "FECHAENTRADA"、"Extent1"。"DIASEMANAOPERAR" 作为 "DIASEMANAOPERAR"、"Extent1"。"TIPOCONTRATO" 作为 "TIPOCONTRATO"、"Extent1"。"PERIODICIDAD" 作为 "PERIODICIDAD"、"Extent1" .“DESC_PERIODICIDAD”作为“DESC_PERIODICIDAD”,“Extent1”。“ACTIVO”作为“ACTIVO”,“Extent1”。“MA_TYPE”作为“MA_TYPE”,“Extent1”。MA_VERSION”作为“MA_VERSION”,“Extent1”。“COLLATERALPORTFOLIOCODE”作为“CKCOL_ADM”的“COLLATERALPORTFOLIOCODE”。“CECA_SPECIAL_CA”“Extent1”在哪里((“Extent1”。“IDACUERDO”= MiCpty)和(“Extent1”。“FECHAENTRADA " = 2013 年 10 月 31 日 00:00:00))

于 2013-10-31T07:41:42.520 回答
0

您可以使用 sql server 2008 工具“Sql Server Profiler”查看执行的查询。

于 2013-10-31T10:03:20.377 回答