What does adding Name and Namespace to DataContract do?

Johann's answer, IMO is the correct one.

It works this way because when you send SOAP messages, the elements need to be namespace qualified, otherwise the WCF doesnt know how to deserialize the SOAP into the User data contract because of the namespace mismatch.

In C#, these two objects are different because they are in different namespaces...

namespace UserServices
{
    public class User
    {
        public string FirstName { get; set; }
    }
}

namespace TempuriServices
{
    public class User
    {
        public string FirstName { get; set; }
    }
}

The Namespace in XML / SOAP serves the same purpose, to make sure the objects are from the same "body" / "company" / "organization" / "domain" etc.

From what I have found, when I build SOAP services, I tend to keep all of my data contracts, service contracts, and binding namespaces in the same namespace, e.g. "http://mycompany.com/services/serviceName"

here are some great resources... Data Contract Equivalence => http://msdn.microsoft.com/en-us/library/ms734767.aspx Data Contract Versioning Best Practices => http://msdn.microsoft.com/en-us/library/ms733832.aspx

Hope this helps.


In additional to the other answers, the Namespace in a DataContract allows for two objects of the same name in different namespaces - i.e. versioning.

These two objects are allowed to exist as different properties in a WSDL and will be known deserializable types provided they have different namespaces:

[DataContract(Namespace = "http://myservice/v1/thing")]
V1.Thing

[DataContract(Namespace = "http://myservice/v2/thing")]
V2.Thing

Of course, they need to exist in your C# code as well for it to be valid. Or, alternatively you can change the name that the objects are known by using the Name attribute for clarity.

[DataContract(Name = "Thing")]
V1.Thing

[DataContract(Name= = "newThing")]
V2.Thing

You might use this when the class' name has changed in your project, but you need to support existing clients that use the 'old' names.

In summary, the Name and Namespace properties control how your objects will be serialized and deserialized when transmitted over the wire. When you set them, you are controlling how the client will see your data contract.


These properties control the namespace and name of the element in the WSDL. The important part in your code is the Namespace="": this will override the default namespace (http://tempuri.org) and set its value to an empty URL.

In the end, the User class will be renamed in the WSDL from http://tempuri.org/User to simply User.

Tags:

C#

Wcf