Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use DataContract and Serializable together?

I am working on WCF service. My all class are already serialize using [Serializable] attribute but due to "k__BackingField" Property Naming problem I used DataContract and DataMember attribute. so Can i use both attribute together like following:

[Serializable]
[DataContract]
public class User
{

  [DataMember]
  public string Name { get; set; }

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

is this correct?

I also got similar solution here. C# automatic property deserialization of JSON

Serializable and DataContract (not versus?)

like image 701
Rajesh Kumar Avatar asked Mar 23 '11 12:03

Rajesh Kumar


People also ask

How do you serialize Datacontract?

To prepare a class for serialization, apply the DataContractAttribute to the class. For each member of the class that returns data that you want to serialize, apply the DataMemberAttribute. You can serialize fields and properties, regardless of accessibility: private, protected, internal, protected internal, or public.

Is Datacontract mandatory in WCF?

No, the DataContractAttribute is not required - WCF will infer serialization rules.

Why Datacontract is used in WCF?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts.

What is Datacontract and DataMember?

A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.


2 Answers

I found an article on MSDN according to this we can use both attribute DataContract and Serializable together.

With [Serializable], all fields become part of the data contract (unless they are marked with [NonSerialized]). With [DataContract], only members marked with [DataMember] are included. Note that if a type has both [DataContract] and [Serializable] attributes on it, it will use the [DataContract] mapping

http://msdn.microsoft.com/en-us/magazine/cc163569.aspx

like image 195
Rajesh Kumar Avatar answered Oct 10 '22 04:10

Rajesh Kumar


if the problem is in naming why don't you use

[XmlElement(ElementName = "Name")] public string Name { get; set; }  
like image 36
Alexander Efimov Avatar answered Oct 10 '22 02:10

Alexander Efimov