mr.*_*eze 28 c# entity-framework
在Entity Framework 6中,是否可以在调用SaveChanges 之前查看将为插入 执行的SQL ?
using (var db = new StuffEntities()){
db.Things.Add(new Thing({...});
//can I get the SQL insert statement at this point?
db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
我很熟悉如何在执行之前为查询生成生成的SQL,如下所示:
var query = db.Thing.Where(x => x.ID == 9);
Console.WriteLine(query.ToString());
//this prints the SQL select statement
Run Code Online (Sandbox Code Playgroud)
查询返回IQueryable <>,而insert返回DbSet并在DbSet上调用ToString只打印标准对象名称.
Sve*_*sen 16
另一种选择(如果我正确地理解你的问题),是使用一个IDbCommandInterceptor实现,这似乎可以让你检查SQL命令在执行之前(我对冲我的话,因为我没有用过这个我自己).
像这样的东西:
public class CommandInterceptor : IDbCommandInterceptor
{
public void NonQueryExecuting(
DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
// do whatever with command.CommandText
}
}
Run Code Online (Sandbox Code Playgroud)
DBInterception在上下文静态构造函数中使用EF中可用的类注册它:
static StuffEntities()
{
Database.SetInitializer<StuffEntities>(null); // or however you have it
System.Data.Entity.Infrastructure.Interception.DbInterception.Add(new CommandInterceptor());
}
Run Code Online (Sandbox Code Playgroud)
Ger*_*ius 16
EF6中最简单的方法要在不更改代码的情况下使查询始终方便,就是将其添加到DbContext中,然后在调试时检查visual studio中输出窗口上的查询.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.Log = (query)=> Debug.Write(query);
}
Run Code Online (Sandbox Code Playgroud)
编辑
LINQPad也是调试Linq的一个很好的选择,也可以显示SQL查询.
Iva*_*oev 11
没有相当于query.ToString()AFAIK的东西.你最终可以使用DbContext.Database.Log属性:
db.Database.Log = s =>
{
// You can put a breakpoint here and examine s with the TextVisualizer
// Note that only some of the s values are SQL statements
Debug.Print(s);
};
db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
使用拦截器获取详细信息,请参阅此链接
将其添加到.config文件中
<interceptors>
<interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
<parameters>
<parameter value="C:\Temp\LogOutput.txt"/>
</parameters>
</interceptor>
</interceptors>
Run Code Online (Sandbox Code Playgroud)