CRM 2011: Early Binding C#- error while retrieve and save data

If you’re using Early Binding with CRM 2011 and facing one of the following issues… you’ve landed on the right page!!

While retrieving the data using LINQ:
Exception Type: ArgumentException
Message: Object of type ‘Microsoft.Xrm.Sdk.Entity’ cannot be converted to type ‘XXX’.

OR

Updating the data using LINQ:
Exception Type: SaveChangesException
Message: An error occured while processing this request.
Inner Exception: {“Value cannot be null.rnParameter name: value”}

You probably forgot to add a behavior to the OrganizationServiceProxy object given as below.

serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

This statement is required to enable early-bound type support.

Enjoy!

CRM 2011 Error: Object of type 'Microsoft.Xrm.Sdk.Entity' cannot be converted to Type

While I was working with Querying Contact data for CRM 2011 through LINQ, I faced this error which says:

Object of type ‘Microsoft.Xrm.Sdk.Entity’ cannot be converted to Contact

My code goes like this:

OrgService = new OrganizationServiceProxy(OrgServiceUri, null, this.ccreds, this.dcreds);
using (var context = new CrmDataContext(OrgService))
{
    var query = from contacts in context.ContactSet
                select new Contact
                {
                    FirstName = contacts.FirstName,
                    Address1_Country = contacts.Address1_Country
                };

    foreach (var contact in query)
    {
        ContactsListBox.Items.Add(contact.FirstName);
    }
}

After little searching on the net for this error, I got the solution to prevent this error. You need to add following statement:

OrgService.EnableProxyTypes();

I got the reference from this. And it is required to enable support for Early bound entity types.