Search code examples
c#entity-frameworkwcf-data-servicesodatawindows-phone

Is it possible to update a WCF Data Service (oData) entity without performing a query first?


I've been racking my brain out with this problem and perhaps I'm not looking at it improperly.

I have a server side architecture which look like this SQL Server --> EF --> WCF Data Service (oData)

Is there is a way to update a server side entity without first querying the server.

From all of the documentation I have read, it appears that a query is required to add the entity into the context for tracking. Once tracked, changes can be made to the entity, then BeginSaveChanges can be called to perform the update.

I am accessing my oData service from a Windows Phone app, where I store the server entity (with its ID) in isolated storage as a POCO object. I do not store the DTO that is created from the WCF proxy client.

I do not want to query the entity first, to save on bandwidth.


Solution

  • Yes there is, you need to create a dummy entity and then attach and save it.

    eg

    using(var ctx = new MyContext())
    {
       var dummyEntity = new MyEntity{ Id = 1 };
       ctx.MyEntities.Attach(dummyEntity); // EF now knows you have an entity with ID 1 in your db but none of its properties have changed yet
       dummyEntity.SomeProperty = 1; //the change to SomeProperty is now tracked
       ctx.SaveChanges();// a single update is called to set entity with Id 1's 'SomeProperty' to 1  
    }
    

    There are some issues with this however, attach will fail if you have any other entities with the same id attached to your context. Because of this its best to keep the scope of your context very small when performing this kind of action.