views:

24

answers:

1

I have a WCF service that uses the entity framework to retrieve records from the database and map them to POCO objects. These POCO objects are then returned to the client application.

Lets say the client application changes some properties on one of these POCO objects then sends it back to the WCF service to be saved. As far as I can see this POCO object is then completely disconnected from the entity framework context. The way I currently save this is to create a new context object and retrieve the POCO object from the database again, I then copy property values of the POCO object passed in to the method in to the POCO object just retrieve from the database then call save on the context. Is this the best way to be doing this or is there a simpler method?

+1  A: 

The problem here is that EF keeps track of attached objects by using it's own 'unique identifier' for each retrieved object, different from the record's primary key in your database. That property is of course not marked with the DataMember attribute, so when sent over the WCF service you lose the key that was used by EF to keep track of it. When deserializing the object, it's no longer the same exact object, but another simpler one containing only the properties marked with the DataMember attribute. So when the service receives them back again, you of course lose the connection between the object and EF.

Have you tried reattaching the object to the context? I think it should work, but i haven't tried it myself.

scripni
you just call the Attach method on the table, supplying your POCO entity as a parameter. it's very straightforward.http://msdn.microsoft.com/en-us/library/bb896271.aspx
scripni
Thanks, I've just tried that and I can get it added to the context using AttachTo however when I call context.SaveChanges() the changes are not reflected in the database. I'm guess this is because the contact doesn't think it has been changed so doesn't save it.
Gavin Draper
Found the problem, because change tracking has been lost you need to manually set it as modified after you attach it by doing something like this context.ObjectStateManager.ChangeObjectState(service, EntityState.Modified);
Gavin Draper
good to know, now i've learned something too
scripni