在实体框架 6 中,是否可以查看将为某个对象执行的 SQLinsert before调用 SaveChanges?
using (var db = new StuffEntities()){
db.Things.Add(new Thing({...});
//can I get the SQL insert statement at this point?
db.SaveChanges();
}
我熟悉如何获取生成的 SQLquery在执行之前像这样:
var query = db.Thing.Where(x => x.ID == 9);
Console.WriteLine(query.ToString());
//this prints the SQL select statement
查询返回 IQueryable,而插入返回 DbSet,并且在 DbSet 上调用 ToString 仅打印标准对象名称。
另一种选择(如果我正确理解你的问题)是使用IDbCommandInterceptor https://msdn.microsoft.com/en-US/data/dn469464实现,它似乎允许您在执行 SQL 命令之前对其进行检查(我自己没有使用过它,所以我要多说几句)。
像这样的事情:
public class CommandInterceptor : IDbCommandInterceptor
{
public void NonQueryExecuting(
DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
// do whatever with command.CommandText
}
}
注册它使用DBInterception
EF 中可用的类在您的上下文静态构造函数中:
static StuffEntities()
{
Database.SetInitializer<StuffEntities>(null); // or however you have it
System.Data.Entity.Infrastructure.Interception.DbInterception.Add(new CommandInterceptor());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)