IT story

DataContract 및 DataMember 특성을 언제 사용합니까?

hot-time 2020. 5. 25. 08:12
반응형

DataContract 및 DataMember 특성을 언제 사용합니까?


DataContractWCF 특성에 대해 매우 혼란스러워합니다 . 내 지식에 따르면 클래스와 같은 사용자 정의 유형을 직렬화하는 데 사용됩니다. 나는 이런 식으로 클라이언트 측에 노출되는 클래스를 작성했습니다.

[DataContract]
public class Contact
{
    [DataMember]
    public int Roll { get; set; }

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

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

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

그것은 제대로 작동하지만 때 제거 DataContract하고 DataMember또한 제대로 작동합니다. 왜 제대로 작동하는지 이해할 수 없습니다. 아무도 실제로 사용하는 것이 무엇인지 말해 줄 수 있습니까 DataContract?

내 서비스 계약은 다음과 같습니다

[ServiceContract]    
public interface IRestServiceImpl
{
    [OperationContract]        
    Contact XmlData(string id);      
}

.NET 3.5 SP1을 사용 하면 많은 프로그래머가 [DataContract]and [DataMember]특성에 압도 되었기 때문에 Microsoft는 데이터 계약 serializer가 해당 특성이 없어도 이전 XML serializer와 마찬가지로 모든 클래스를 처리하도록했습니다.

그래서 .NET 3.5 SP1의, 당신이하지 않는 해야 할 데이터 계약 또는 데이터 구성원을 추가하는 것은 더 이상 속성 - 그렇게하지 않으면 다음 데이터 계약 시리얼 라이저는 클래스의 모든 공용 속성을 직렬화 할 것이다 단지 XML 시리얼 같은 것.

그러나 이러한 속성을 추가하지 않으면 유용한 기능이 많이 손실됩니다.

  • 이 없으면 [DataContract]데이터를 저장할 XML 네임 스페이스를 정의 할 수 없습니다.
  • 이 없으면 [DataMember]비공개 속성 또는 필드를 직렬화 할 수 없습니다.
  • 이없는 [DataMember]경우 직렬화 순서 ( Order=)를 정의 할 수 없으며 DCS는 모든 속성을 알파벳순으로 직렬화
  • 이 없으면 [DataMember]속성 ( Name=)에 다른 이름을 정의 할 수 없습니다
  • 없이는 [DataMember]유사 IsRequired=하거나 다른 유용한 속성을 정의 할 수 없습니다
  • 없이는 [DataMember]특정 공공 자산을 제외 할 수 없습니다. 모든 공공 자산은 DCS에 의해 일련 화됩니다.

따라서 "빠른 '더러운"솔루션의 경우 속성 [DataContract][DataMember]속성을 없애면 작동하지만 데이터 클래스에 포함시키는 것은 좋은 생각입니다. 당신이 그들없이 얻을 수없는 모든 추가 기능에 액세스 ...


WCF 측면에서 메시지를 통해 서버 및 클라이언트와 통신 할 수 있습니다. 메시지를 전송하고 보안을 위해 데이터 / 메시지를 직렬화 된 형식으로 만들어야합니다.

데이터를 직렬화하기 위해 [datacontract] 및 [datamember] 속성을 사용합니다. 귀하의 경우에는 당신이 사용하는 경우 datacontractWCF에서 사용하는 DataContractSerializer다른 WCF가 사용하는 XmlSerializer기본 직렬화 기술이다.

자세히 설명하겠습니다 :

기본적으로 WCF는 3 가지 유형의 직렬화를 지원합니다.

  1. XmlSerializer
  2. DataContractSerializer
  3. NetDataContractSerializer

XmlSerializer :-기본 순서는 클래스와 동일

DataContractSerializer / NetDataContractSerializer :-기본 순서는 알파벳순

XmlSerializer :-XML 스키마가 광범위하다

DataContractSerializer / NetDataContractSerializer :-XML 스키마가 제약 됨

XmlSerializer :-버전 관리 지원 불가

DataContractSerializer/NetDataContractSerializer :- Versioning support is possible

XmlSerializer :- Compatibility with ASMX

DataContractSerializer/NetDataContractSerializer :- Compatibility with .NET Remoting

XmlSerializer :- Attribute not required in XmlSerializer

DataContractSerializer/NetDataContractSerializer :- Attribute required in this serializing

so what you use depends on your requirements...


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. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Many .NET Framework types also have existing data contracts.

You can find the full article here.


A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.

Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute.

A data contract can be defined as follows:

  • It describes the external format of data passed to and from service operations

  • It defines the structure and types of data exchanged in service messages

  • It maps a CLR type to an XML Schema
  • It defines how data types are serialized and deserialized. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through deserialization, you reassemble an object from a sequence of bytes that you receive from a calling application.
  • It is a versioning system that allows you to manage changes to structured data

We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract and DataMember attribute.


  1. Data contract: It specifies that your entity class is ready for Serialization process.

  2. Data members: It specifies that the particular field is part of the data contract and it can be serialized.


Also when you call from http request it will work properly but when your try to call from net.tcp that time you get all this kind stuff


DataMember attribute is not mandatory to add to serialize data. When DataMember attribute is not added, old XMLSerializer serializes the data. Adding a DataMember provides useful properties like order, name, isrequired which cannot be used otherwise.

참고URL : https://stackoverflow.com/questions/4836683/when-to-use-datacontract-and-datamember-attributes

반응형