使用EF4,是否可以获取生成的sql for Updates / Inserts而不是执行它…就像您可以在运行之前查看sql一样.
- Decrement<Category>("ProductCount",categoryID);
- SetNull<Product>("CategoryID",productID);
哪个生成…
- UPDATE Categories
- SET ProductCount = ProductCount - 1
- WHERE CategoryID = @CategoryID;
- UPDATE Products
- SET CategoryID = NULL
- WHERE CategoryID = @ProductID;
我通常每个操作运行几个命令,所以在每个帮助函数调用时,sql被生成和存储.当我调用SaveChanges()时,所有命令都在一次运行.
唯一的问题是EF会在幕后分开运行命令,然后我运行其他命令.将所有内容作为一个命令运行是理想的.
解决方法
您可以在设计时使用sql Profiler获得它,但我认为您的意思是您希望在运行时.这里有一个例子,我发现如何做到这一点:
- public static void WriteGeneratedsql(EntityCommand cmd)
- {
- cmd.Prepare();
- IServiceProvider isp = (IServiceProvider)EntityProviderFactory.Instance;
- DbProviderServices mps = (DbProviderServices)isp.GetService(typeof(DbProviderServices));
- EntityCommandDefinition definition = (EntityCommandDefinition)mps.CreateCommandDefinition(cmd);
- int commandId = 1;
- foreach (string commandText in definition.MappedCommands)
- {
- Console.WriteLine("Generated Command {0}:",commandId);
- commandId++;
- Console.WriteLine(commandText);
- }
- }
发现here.