2012-10-29

EF POCO objects and WCF

We have recently started to use Entity Framework using a Code First approach, including POCO classes. However, when we tried to use POCO object classes as parameters of web service calls, we got the following exception:

System.ServiceModel.CommunicationException: There was an error while trying to serialize parameter http://tempuri.org/:foo. The InnerException message was 'Type 'System.Data.Entity.DynamicProxies.FooClass_F952F109218D94AD325682E75C75F0EFF0D59311269F52F267E249FB9D8F7196' with data contract name 'FooClass_F952F109218D94AD325682E75C75F0EFF0D59311269F52F267E249FB9D8F7196:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'.  Please see InnerException for more details.

What's happening? Well, it happens that a runtime, POCO objects are not really POCO, but proxies that wrap the original POCO objects. WCF knows the POCO type, but not the subtype of the proxy class. How to fix it? There are several approaches, we just opted by a simple workaround: all our classes that need to be passed as parameters for a web service calls now implement ICloneable interface and are cloned just before the call.

Perhaps a more elegant approach would be using a specific class for the parameter of the WCF service and implement a mapper between the two types, but if you need a quick workaround the clone approach does the trick.

No comments:

Post a Comment