Advertisements

Archive

Archive for January 3, 2012

“The context is not currently tracking the entity” exception in CRM 2011

January 3, 2012 1 comment

Hi,

You may come across below exception when you are trying to Create/Update child record in the Parent record context of Plug-in using XRM Linq

Context is not currently tracking entity

Context is not currently tracking entity

Scenario :-

  • Imagine you have registered a “Post Update” Plug-in on ‘Account’ entity which Updates an associated ‘Contact’ entity
  • Here the Plug-in runs under Parent Entity Context (i.e., Account)
  • When you try to update child record (i.e.,Contact) it throws out exception, since the context knows nothing about ‘Contact’

Fix :-

  • The solution is call the context.Attach() method; Call this method before calling the Update method (Refer below code)

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

var ServiceContext= new XrmServiceContext(service);

Guid contactGUID= (from c in xrm.ContactSet where c.FullName == “Farest Chand” select c.Id).FirstOrDefault();

ServiceContext.Contact objContact= new ServiceContext.Contact {  Id = contactGUID,  FullName= ‘Rajeev’};

ServiceContext.ClearChanges();

ServiceContext.Attach(objContact);

ServiceContext.UpdateObject(objContact);

ServiceContext.SaveChanges();

Hope it Helps 🙂

Advertisements