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

1

7

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?

Liborio answered 7/1, 2011 at 14:45 Comment(2)
No, I don't know of any other way. So either you will need to accept that single attribute on your POCO class to make use of those great features - or then just don't use WCF Data Services....Richmal
I'm not that much of a purist, so if there is no alternative I will use it, just want to make sureLiborio
G
10

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

Goddamn answered 10/1, 2011 at 23:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.