I love using the XrmServiceContext Caching issue in order to use LINQ queries to retrieve items from our CRM implementation. So much nicer to work with than the old SOAP model!!!

However, I ran into an issue pretty quickly with a custom service I created that provisions a SharePoint team site for a CRM opportunity. I was getting intermittent caching errors. The script’s attempt to retrieve the opportunity record from CRM would result in the following error:

Sequence contains no elements

I researched the issue and was unable to find a way to configure caching and even attempted to explicitly remove items from the cache, but the only thing that worked for me was to dispose and recreate the XrmServiceContext object as follows:

private void RefreshContext() {
if (context != null) {

ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = MscrmWebService.LoginName;
credentials.UserName.Password = MscrmWebService.Password;
string link = MscrmWebService.Link;
Uri organizationUri = new Uri(MscrmWebService.Link);
Uri homeRealmUri = null;

using (serviceProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null)) {
serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
service = (IOrganizationService)serviceProxy;
context = new XrmServiceContext(service);

public Opportunity RetrieveOpportunity(Guid opportunityId) {
return context.OpportunitySet.Where(e => e.OpportunityId == opportunityId).Single();