2011-02-08 80 views
10

使用EF4,是否有可能爲更新/插入獲取生成的SQL,而不是執行它?就像您可以在運行之前查看查詢SQL一樣。實體框架4 - 獲取更新/插入生成的SQL

原因是,我有一組執行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在後臺單獨運行它的命令,然後我在後面運行其他命令。將所有內容作爲一個命令運行是理想的。

回答

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); 
    } 
} 

找到here

+0

感謝這個答案,但它不是我所需要的。插入新對象或檢索然後更新現有對象後,我需要獲取爲這些操作生成的SQL。我無法從ObjectContext獲取EntityCommand對象。 – 2011-02-10 05:16:26