WCF CollectionDataContract

I recently noticed that in one of the articles, the wcf service service returned the collectiondatacontract command

Users GetUsers(string someInput); 

And the type of users was defined as follows:

 [CollectionDataContract] public class Users : List<User> { public Users() { } public Users(IEnumerable<User> users) : base(users) { } } 

Does collectiondatacontract (for example, Users in this case) return a different purpose than just returning a List<User> ?

+6
source share
3 answers

As far as I understand, this attribute will give you some control over what names the elements in the final xml string will have after the DataContractSerializer has serialized your collection.

This can be useful when you have to manually analyze the result manually (in other words, you will know which element to look for in this XML text, find your collection and its parts).

Take a look at this for examples and more info:

http://msdn.microsoft.com/en-us/library/aa347850.aspx

+4
source

if you return the list, the data serializer has a certain way of generating xml. I don’t know how this is done for List, but if it were an array, it would create something like: ... here is User Object 1 ... etc.

But using CollectionDataContract, you can serialize it and better expose it to consumers who can create XML manually. Example - I could give - CollectionDataCOntract (Name = "AllUsers") // I don’t remember ItemName or Name

then the expected XML will be something similar - ... here is User Object 1 ... etc.

There is one utility for this.

+1
source

Just to explain the answer to Andrey and share my experience, I just went through a problem that I finally solved with CollectionDataContract. In principle, to interact with a specific system, I wanted to be able to send and receive xml format:

 <SomeMessageList> <Message> <ID>blah</ID> <data1>blah</data1> <data2>etc.etc.</data2> </Message> <Message> <ID>blah</ID> <data1>blah</data1> <data2>etc.etc.</data2> </Message> //any number of repeated <Message> here </SomeMessageList> 

However, if I used an array or List object, the root tag was always called ArrayOfMessage. And if I created a class that contained an array of Message objects (for example, called MsgList), then WCF will add this as an additional tag to the mix that I could not find to get rid of it. So it would look like this:

 <SomeMessageList> <MsgList> <Message> <ID>blah</ID> <data1>blah</data1> <data2>etc.etc.</data2> </Message> //any number of repeated <Message> here </MsgList> </SomeMessageList> 

So CollectionDataContract just gave me an easy way to control the name of the root list item.

0
source

Source: https://habr.com/ru/post/886346/


All Articles