Adam Caviness
Adam Caviness

Reputation: 3484

Are there any events or hooks for DataServiceContext.SaveChanges()

There is no built in property level change tracker in WCF Data Services Client so I have created my own property change tracker.

After a caller invokes DataServiceContext.SaveChanges(), I would like to clear my tracked modified properties collection. I don't see any events or hooks that allow me to know when SaveChanges() is called. Are there any events or hooks that I am missing that would allow me to do this more cleanly than hiding the underlying SaveChanges() with my derived DataServiceContext?

Upvotes: 2

Views: 936

Answers (2)

Dave A-W
Dave A-W

Reputation: 665

The hooks at http://blogs.msdn.com/b/astoriateam/archive/2013/07/26/using-the-new-client-hooks-in-wcf-data-services-client.aspx can certainly be used to tie into the SaveChanges() call. If the save results in tracked entities being pushed as an insert or update, then they are accessible during the RequestPipeline's OnEntryEnding hook.

For example, I use the same hook to remove unchanged (clean) properties from the insert/update request:

    public BaseContext(Uri serviceRoot, DataServiceProtocolVersion maxProtocolVersion) :
        base(serviceRoot, maxProtocolVersion)
    {
        this.Configurations.RequestPipeline.OnEntryEnding(OnWritingEntryEnding);
    }

    private static readonly EntityStates[] _statesToPatchIfDirty = 
    { 
        EntityStates.Added, EntityStates.Modified 
    };

    /// <summary>
    /// Removes unmodified and client-only properties prior to sending an update or insert request to the server.
    /// </summary>
    protected virtual void OnWritingEntryEnding(WritingEntryArgs args)
    {
        var editableBase = args.Entity as EditableBase;
        if (editableBase != null 
            && editableBase.IsDirty 
            && _statesToPatchIfDirty.Contains(GetEntityDescriptor(args.Entity).State))
        {
            var cleanProperties = args.Entry
                                      .Properties
                                      .Select(odp => odp.Name)
                                      .Where(p => !editableBase.IsDirtyProperty(p))
                                      .ToArray();
            args.Entry.RemoveProperties(cleanProperties);
        }
    }

You could remove them from your modified properties collection at the same time. However, you'll probably still want to add some handling around SaveChanges() in case the final request errors.

Upvotes: 2

mubcarb
mubcarb

Reputation: 161

below post from WCF Data Service blog might be able to help u:

http://blogs.msdn.com/b/astoriateam/archive/2013/07/26/using-the-new-client-hooks-in-wcf-data-services-client.aspx

Upvotes: 0

Related Questions