Search This Blog

Tuesday, November 22, 2011

LINQ to CRM Caching Issue

Recently I was given the task to create a fairly simple ASP.NET application to import records to a Microsoft Dynamics CRM 4.0 system from an Excel file. I was using LINQ to CRM and because some of the records being created were immediately required to link to other new records, I had to commit changes to the CRM database fairly frequently, and then immediately pull the newly created record.

Things were running along quite smoothly, when suddenly I started getting errors that the newly created record didn't exist. I could clearly see the record in CRM, so I knew it was being created, but could not figure out why it was suddenly not being found. It finally occurred to me that the original dataset was being cached, and was not being refreshed on subsequent requests.

After a little searching, I came upon a forum posting describing the same issue I was having, with a solution that worked like a charm for me. Hopefully it will help someone else out there.

I added the following method to my code, and right before I tried to retrieve the newly created record, I called it to clear the cache so that the dataset would be refreshed.

public static void ClearCache(string entityName)
{
    const string format = "adxdependency:crm:entity:{0}";
    var dependency =
        string.Format(format, entityName).ToLower();
    var cache = Microsoft.Xrm.Client.Caching.CacheManager.GetBaseCache();
    cache.Remove(dependency);
}
This solution worked perfectly for me, I hope it helps someone else out there.

No comments:

Post a Comment