Create records in CRM 2011 using the CRM Web Service

When I began to create records in CRM using the webservice, I started with records containing simple text fields. And there was no problem. The following method creates a new contact entity in CRM:

public static Guid createCandidate(OrganizationServiceClient serviceProxy, string firstname, string lastname, string email)
{

Entity application = new Entity() { LogicalName = "contact" };

// Set Contact Properties
AttributeCollection Attributes = new AttributeCollection();

Attributes.Add(new KeyValuePair<string, object>("firstname", firstname));
Attributes.Add(new KeyValuePair<string, object>("lastname", lastname));
Attributes.Add(new KeyValuePair<string, object>("emailaddress2", email));

application.Attributes = Attributes;

//Create Contact
Guid appGuid = serviceProxy.Create(application);

return appGuid;
}

But then I also wanted to fill OptionSet fields (DropDowns) and ReferenceEntity fields (LookUp). But the Webservice always threw an exception:

Die InnerException-Nachricht war “Der Typ “*.OptionSetValue” mit dem Datenvertragsnamen “OptionSetValue:http://schemas.microsoft.com/xrm/2011/Contracts” wurde nicht erwartet. Fügen Sie alle statisch nicht bekannten Typen der Liste der bekannten Typen hinzu. Verwenden Sie dazu z. B. das Attribut “KnownTypeAttribute”, oder fügen Sie die Typen der an DataContractSerializer übergebenen Liste von bekannten Typen hinzu.”.

After a long time I found the solution here:

1. Create a new class in your project with name you prefer.

2. Keep the namespace of this class similar to your Reference.cs (This is important so do not forget it)

3. Now create partial classes as below

[System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]
public partial class Entity { }

[System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]
public partial class EntityCollection { }

[System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(PrincipalAccess))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]
public partial class OrganizationRequest { }

4. Now go to your actual code, and for lookup field use like this:

Attributes.Add(new KeyValuePair<string,object>("parentcustomerid", new EntityReference() {Id = t.Id, LogicalName= t.LogicalName}));

5. Build the solution

Now everything should work as expectedt!