简体   繁体   English

从实体框架中的 DbContext 生成数据脚本

[英]Generate data script from DbContext in entity framework

I am working on entity framework and would want to generate and insert/update/delete script from the DbContext object, when changes are about to be saved.我正在研究实体框架,并希望在即将保存更改时从 DbContext 对象生成和插入/更新/删除脚本。 As of now I have only been able to get the DDL script from the context, by using the following snippet.到目前为止,我只能使用以下代码段从上下文中获取 DDL 脚本。

string str = ((IObjectContextAdapter)_objDataContext).ObjectContext.CreateDatabaseScript();

Is there a way to generate a script for all the changes?有没有办法为所有更改生成脚本?

There isn't any built-in way to generate DML scripts for changes before the SaveChanges() method is called, but it is possible to intercept insert/update/delete commands as they are being sent to the DB after SaveChanges() has been called.没有任何内置方法可以在调用SaveChanges()方法之前为更改生成 DML 脚本,但是可以拦截插入/更新/删除命令,因为它们在SaveChanges()被发送到数据库后叫。

EF 6 introduced two extensibility points for such scenarios. EF 6 为此类场景引入了两个扩展点。

It it possible to set the _objDataContext.Database.Log property a TextWriter , where all SQL commands issued by the context will be logged.可以将_objDataContext.Database.Log属性设置为TextWriter ,其中将记录上下文发出的所有 SQL 命令。

Another option is implementing an interceptor, that is called by the EF when it is about to execute a command or after the command has been executed.另一种选择是实现拦截器,EF 在即将执行命令或命令执行后调用该拦截器。 Interceptors allow you to log the SQL command being sent and even provide a way to suppress execution of the command.拦截器允许您记录正在发送的 SQL 命令,甚至提供一种抑制命令执行的方法。

To create an interceptor you need to write a class that implements the IDbCommandInterceptor interface and register this class in Entity Framework.要创建拦截器,您需要编写一个实现IDbCommandInterceptor接口的类,并在实体框架中注册此类。

DbInterception.Add(new MyInterceptor());

For more details you can see a sample implementation on MSDN .有关更多详细信息,您可以在 MSDN 上查看示例实现


A solution for older versions of the Entty Framework might be a wrapping provider around your current db provider.旧版本的 Entty 框架的解决方案可能是围绕您当前的 db 提供程序的包装提供程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM