none
Change Self Tracking Entities to only include "modified" properties RRS feed

  • Question

  • Hi,

    I'm working with Self tracking entities with EF 4.1. I've got a silverlight client, WCF web servcie and SQL database (database first approach). Currently changing a single property of an entity and saving it back on the server is causing all columns to be updated. I now want to implement an auditing manager so I want to inspect the object state manager and find out only which columns have been modified etc. I understand that by default the STEs track a change to the entity, rather than individual properties, hence I'm seeing the behaviour I currently get.  

    When reading on the net about how to track and hence modify only those properties that have changed, I read this post http://blogs.msdn.com/b/adonet/archive/2011/02/09/self-tracking-entities-original-values-and-update-customization.aspx

    which explains a solution is to edit the templates and that's that. I edited the files as shown below:

    From: OriginalValueMembers originalValueMembers = new

              OriginalValueMembers(allMetadataLoaded, metadataWorkspace, ef);

    To: OriginalValueMembers originalValueMembers = new

              OriginalValueMembers(false, metadataWorkspace, ef);

    and then

     context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);

    tocontext.ObjectStateManager.ChangeObjectState(entity, EntityState.Unchanged);

    However, this just doesn't work for me. The SaveChanges method returns 0. I've looked at SQL profiler and no SQL is executed when running SaveChanges. 

    Has anybody got any ideas what could be wrong?

    Thanks 

    Monday, June 11, 2012 9:06 PM

Answers

  • Hi rockshire,

    I have tested the solution in that link, it works well in my machine. I have an entity named 'Person' which has 4 properties - id,name,sex,age. Below is the code.

    static void Main(string[] args)
            {
                using (TestEntities context = new TestEntities())
                {
                    Person person = context.People.FirstOrDefault();
                    person.name = "abc";                
                    context.SaveChanges();
                }
            }

    and the generated T-SQL which I got from SQL SERVER Profiler looks like below.

    exec sp_executesql N'update [dbo].[People]
    set [name] = @0
    where ([id] = @1)
    ',N'@0 nvarchar(50),@1 int',@0=N'abc',@1=1

    Please double check the T4 template which you modified.

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Wednesday, June 13, 2012 7:37 AM
    Moderator