3

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is just the thing that i was searching for! also something that might help others: StringBuilder sb = new StringBuilder(); dbContext.Database.Log = s => sb.AppendLine(s);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.