Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF DataService, how do I avoid [DataServiceKey] in POCOs

I use a WCF DataService and want to use POCOs. I have to specify a DataServiceKey in order for it to work (obviously). When I do that I have to reference System.Data.Services.Client (for System.Data.Services.Common) - which doesn't feel very POCO.

Is there a way to keep my objects clean and specify the Key somewhere else?

like image 920
Christina Mayers Avatar asked Jan 07 '11 14:01

Christina Mayers


1 Answers

If you're using a reflection provider and your classes don't follow a convention for key properties, then you have to use the DataServiceKey attribute. Reflection provider is the one you get if you simply provide class definitions and context class to the DataService. So if you don't implement IDataServiceMetadataProvider, you're very likely using a reflection provider. It is possible to use reflection provider without the attributes on your classes, but then the WCF Data Services applies a heuristics to figure out the key properties. It goes like this:

  • if the class in question has a property called ID, it's an entity with the ID as the only key property.
  • if the class is called for example Customer and it has a property called CustomerID, it's an entity with the CustomerID property as the only key property (the name of the class is obviously just as sample).

No other properties are recognized as key properties without the DataServiceKey attribute. This is also described for example in this blog: http://blogs.msdn.com/b/alexj/archive/2010/06/11/tip-56-writing-an-odata-service-using-the-reflection-provider.aspx

It is possible to use 100% POCO classes with arbitrary key properties, but then you would have to implement a custom provider. This is considerably more work since you have to define the shape of your classes programatically. A sample custom provider walkthrough can be found here: http://blogs.msdn.com/b/alexj/archive/2010/01/07/data-service-providers-getting-started.aspx

like image 56
Vitek Karas MSFT Avatar answered Oct 19 '22 04:10

Vitek Karas MSFT