WCF datacontract vs class serialize
Asked Answered
C

2

7

I understand that we can have more controls on a class if we use datacontract, however, consider the following 2 cases

[DataContract]
public class Customer
{
    [DataMember]
    public string CustomerName {get; set;}

    [DataMember]
    public int Age{get; set;}
}

and

public class Customer
{
    public string CustomerName {get; set;}
    public int Age{get; set;}
}

They both get serialized correctly on .net client. And personally I do not use second example. Can anybody point me the differences in the 2 classes? I meant to send all public properties in both classes.

Compressive answered 18/1, 2011 at 8:55 Comment(1)
@decyclone Thank you very much for the layout fix, I tried several times but still got the annoying first line blank problem.Compressive
E
5

The second version is the POCO (plain old CLR object) version of your data contract and can be used with WCF since 3.5 sp1.

I would not recommend using it though as it gives you very little control on the serialization (namespace attributes...) and it couples your service entities with your business entities (which can be same with POCO)

Eldest answered 18/1, 2011 at 8:59 Comment(2)
Will second version be exposed by wsdl?Compressive
@Yuan: After WCF 3.5 SP1, Yes.Vicinal
C
3

Anyway here is a better story from "Programming WCF services, 3rd Edition"

While using the Serializable attribute is workable, it is not ideal for service-oriented interaction between clients and services. Rather than denoting all members in a type as serializable and therefore part of the data schema for that type, it would be preferable to have an opt-in approach, where only members the contract developer wants to explicitly include in the data contract are included. The Serializable attribute forces the data type to be serializable in order to be used as a parameter in a contract operation, and it does not offer clean separation between the ability to use the type as a WCF operation parameter (the “serviceness” aspect of the type) and the ability to serialize it. The attribute offers no support for aliasing type names or members, or for mapping a new type to a predefined data contract. The attribute operates directly on member fields and completely bypasses any logical properties used to access those fields. It would be better to allow those properties to add their values when accessing the fields. Finally, there is no direct support for versioning, because the formatter supposedly captures all versioning information. Consequently, it is difficult to deal with versioning over time.

Compressive answered 23/3, 2011 at 23:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.