实体框架4 - 获取更新/插入的生成SQL

Ste*_*ols 10 entity-framework entity-framework-4

使用EF4,是否可以获取生成的更新/插入SQL而不是执行它......就像您可以在运行之前查看查询SQL一样.

原因是,我有一组执行SQL命令的辅助函数.例如...

Decrement<Category>("ProductCount", categoryID);
SetNull<Product>("CategoryID", productID);
Run Code Online (Sandbox Code Playgroud)

哪个产生......

UPDATE Categories 
SET ProductCount = ProductCount - 1 
WHERE CategoryID = @CategoryID; 

UPDATE Products 
SET CategoryID = NULL 
WHERE CategoryID = @ProductID;
Run Code Online (Sandbox Code Playgroud)

我通常在每个操作中运行几个命令,因此在每个辅助函数调用时,都会生成并存储SQL.当我调用SaveChanges()时,所有命令都是一次运行的.

唯一的问题是EF在幕后单独运行命令,然后我立即运行其他命令.将所有内容作为单个命令运行是理想的.

Chr*_*ens 5

您可以在设计时使用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);
     }
}
Run Code Online (Sandbox Code Playgroud)

这里找到.