Search code examples
dynamics-crmcrmdynamics-crm-2015

Updating an entity record in CRM using Entity Framework


I been trying lately to update records in CRM 2015 Entity using the auto generated code from the SDK tool of CRM CrmSvcUtil.exe using the code

CrmConnection con = new CrmConnection("CRM");
XrmServiceContext ctx = new XrmServiceContext(con);
var nn = ctx.TestEntity.Where(x => x.Name== "12132").FirstOrDefault();
nn.Name="test";
ctx.SaveChanges();

but all the changes done are ignored after save Changes, I noticed that the entity state of the changed record still unchanged.

When using the ctx.UpdateObject(nn); and ctx.Update(mm); the application throws the following errors:

The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://schemas.microsoft.com/xrm/2011/Contracts/Services:request. The InnerException message was 'Error in line 1 position 13371. Element 'http://schemas.datacontract.org/2004/07/System.Collections.Generic:value' contains data from a type that maps to the name 'http://schemas.microsoft.com/xrm/7.1/Contracts:ConcurrencyBehavior'. The deserializer has no knowledge of any type that maps to this name. Consider changing the implementation of the ResolveName method on your DataContractResolver to return a non-null value for name 'ConcurrencyBehavior' and namespace 'http://schemas.microsoft.com/xrm/7.1/Contracts'.'. Please see InnerException for more details.

or this

EntityState must be set to null, Created (for Create message) or Changed (for Update message)

and when trying to set the entity state manually to changed I get this error

The entity is read-only and the 'EntityState' property cannot be modified. Use the context to update the entity instead.

Knowing that I can create new records using the same auto generated code by using ctx.AddObject()


Solution

  • You should use ctx.UpdateObject before calling ctx.SaveChanges().

    UpdateRequest.ConcurrencyBehavior was introduced in CRM 2015 Update 1. It appears to me that you have a mismatch between the version of CRM and the version of CrmSvcUtil you are using. You must be using a newer version of the SDK Tools.

    Since you are using the RTM version of CRM you can download and use the corresponding RTM version of the CRM 2015 SDK core tools (version 7.0.1). After re-generating your context with CrmSvcUtil from that version you should no longer see any errors related to UpdateRequest.ConcurrencyBehavior.