简体   繁体   中英

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. As of now I have only been able to get the DDL script from the context, by using the following snippet.

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.

EF 6 introduced two extensibility points for such scenarios.

It it possible to set the _objDataContext.Database.Log property a TextWriter , where all SQL commands issued by the context will be logged.

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. Interceptors allow you to log the SQL command being sent and even provide a way to suppress execution of the command.

To create an interceptor you need to write a class that implements the IDbCommandInterceptor interface and register this class in Entity Framework.

DbInterception.Add(new MyInterceptor());

For more details you can see a sample implementation on MSDN .


A solution for older versions of the Entty Framework might be a wrapping provider around your current db provider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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