Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

view generated SQL for Entity Framewok SaveChanges command in Visual studio?

I can see the SQL generated by Entity Framework for select operations in Visual studio, but not for insert, update and delete. how can I see the SQL generated for "DataContext.SaveChanges" command in Visual studio while debugging?

like image 860
RKP Avatar asked Mar 02 '12 15:03

RKP


3 Answers

If you have visual studio ultimate you can see the updates and inserts in intellitrace. Just put a breakpoint right after SaveChanges is called.

http://www.youtube.com/watch?v=fLBpZNXs-Lw

If you are using it on a web project you could also use mini-profiler.

http://miniprofiler.com/

like image 123
Jack Woodward Avatar answered Oct 24 '22 08:10

Jack Woodward


Here's something really simple that I found:

context.Database.Log = x => System.Diagnostics.Debug.WriteLine(x);
like image 3
theGleep Avatar answered Oct 24 '22 07:10

theGleep


Have a look at this thread on the MSDN forums; specifically, the post by g_yordanov. He has provided some code which can retrieve the corresponding SQL statements for all of the changes in an EF datacontext.

As a disclaimer, this code involves reflecting on EF's internals, and may break in future versions. But for now, it is working flawlessly in all of our EF apps.

Here is the code, for reference, just in case the link ever disappears.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data.Objects;
using System.Data.Common;
using System.Data.EntityClient;
using System.Collections;

namespace EntityExtensionMethods
{
    public static class CustomExtensions
    {
        private static readonly string entityAssemblyName =
            "system.data.entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

        public static string ToTraceString(this IQueryable query)
        {
            System.Reflection.MethodInfo toTraceStringMethod = query.GetType().GetMethod("ToTraceString");

            if (toTraceStringMethod != null)
                return toTraceStringMethod.Invoke(query, null).ToString();
            else
                return "";
        }

        public static string ToTraceString(this ObjectContext ctx)
        {
            Assembly entityAssemly = Assembly.Load(entityAssemblyName);

            Type updateTranslatorType = entityAssemly.GetType(
                "System.Data.Mapping.Update.Internal.UpdateTranslator");

            Type functionUpdateCommandType = entityAssemly.GetType(
                "System.Data.Mapping.Update.Internal.FunctionUpdateCommand");

            Type dynamicUpdateCommandType = entityAssemly.GetType(
                "System.Data.Mapping.Update.Internal.DynamicUpdateCommand");

            object[] ctorParams = new object[]
                        {
                            ctx.ObjectStateManager,
                            ((EntityConnection)ctx.Connection).GetMetadataWorkspace(),
                            (EntityConnection)ctx.Connection,
                            ctx.CommandTimeout
                        };

            object updateTranslator = Activator.CreateInstance(updateTranslatorType,
                BindingFlags.NonPublic | BindingFlags.Instance, null, ctorParams, null);

            MethodInfo produceCommandsMethod = updateTranslatorType
                .GetMethod("ProduceCommands", BindingFlags.Instance | BindingFlags.NonPublic);
            object updateCommands = produceCommandsMethod.Invoke(updateTranslator, null);

            List<DbCommand> dbCommands = new List<DbCommand>();

            foreach (object o in (IEnumerable)updateCommands)
            {
                if (functionUpdateCommandType.IsInstanceOfType(o))
                {
                    FieldInfo m_dbCommandField = functionUpdateCommandType.GetField(
                        "m_dbCommand", BindingFlags.Instance | BindingFlags.NonPublic);

                    dbCommands.Add((DbCommand)m_dbCommandField.GetValue(o));
                }
                else if (dynamicUpdateCommandType.IsInstanceOfType(o))
                {
                    MethodInfo createCommandMethod = dynamicUpdateCommandType.GetMethod(
                        "CreateCommand", BindingFlags.Instance | BindingFlags.NonPublic);

                    object[] methodParams = new object[]
                    {
                        updateTranslator,
                        new Dictionary<long, object>()
                    };

                    dbCommands.Add((DbCommand)createCommandMethod.Invoke(o, methodParams));
                }
                else
                {
                    throw new NotSupportedException("Unknown UpdateCommand Kind");
                }
            }


            StringBuilder traceString = new StringBuilder();
            foreach (DbCommand command in dbCommands)
            {
                traceString.AppendLine("=============== BEGIN COMMAND ===============");
                traceString.AppendLine();

                traceString.AppendLine(command.CommandText);
                foreach (DbParameter param in command.Parameters)
                {
                    traceString.AppendFormat("{0} = {1}", param.ParameterName, param.Value);
                    traceString.AppendLine();
                }

                traceString.AppendLine();
                traceString.AppendLine("=============== END COMMAND ===============");
            }

            return traceString.ToString();
        }
    }
}
like image 2
Marty Avatar answered Oct 24 '22 09:10

Marty