hanc
hanc

Reputation: 121

Intercept TSQL generated by linq before submitchanges method fire

Is possible intercept TSQL generated by linq before submitchanges() methods fire? I need modify sql insert query.

Upvotes: 1

Views: 261

Answers (2)

Mike Gledhill
Mike Gledhill

Reputation: 29201

Yup, it is possible to intercept the SubmitChanges() call, but not the SQL itself.

In my application, my .dbml file is called "GlobalPricing.dbml", and I have created a class called GlobalPricingDataContext.cs.

public partial class GlobalPricingDataContext: System.Data.Linq.DataContext
{
    public override void SubmitChanges(ConflictMode failureMode)
    {
        int inserts = base.GetChangeSet().Inserts.Count;
        int updates = base.GetChangeSet().Updates.Count;
        int deletes = base.GetChangeSet().Deletes.Count;

        Trace.WriteLine(string.Format("{0}  There are {1} inserts, {2} updates and {3} deletes.", DateTime.Now.ToLongTimeString(), inserts, updates, deletes)); 

        base.SubmitChanges(failureMode);
    }
}

Again, this code won't let you modify the SQL which gets run, but it will at least let you know about what inserts, updates and deletes each of the SubmitChanges() calls is attempting to do.

Upvotes: 0

Kirk Woll
Kirk Woll

Reputation: 77576

You can't modify the SQL as such, but you can intercept the insertion process. Your generated data context should have stubbed-out partial implementations of Insert mehods. For example, if you entity is named, MyDbEntity:

partial void InsertMyDbEntity(MyDbEntity instance);

Since this is partial, you can modify it in the partial class that you've created around the generated data context. You can then use this hook to either generate the INSERT statement out of whole cloth, or alternatively just call a custom stored procedure you've written to handle whatever nuance you're attempting to achieve.

This is the best you can do -- you can't instrument the existing INSERT SQL along the way.

Upvotes: 2

Related Questions