October 17, 2011

Strange behavior of LINQ XRM data context – Ghosts

Recently I experienced a lot of problems when creating a complex plugin which played around with thousands of records.

When using good, old T-SQL you would experience the following behavior:

Id Name
1 AAA
2 BBB
3 CCC

SELECT Name FROM Table WHERE Id = 2
Result: AAA

UPDATE Table SET Name = ‘ZZZ’ WHERE Id = 2

SELECT Id FROM Table WHERE Name = ‘ZZZ’
Result: 2

Being naïve and lazy I expected the same behavior from the LINQ 2 CRM data provider – wrong! Remember about caching. This doesn’t happen every time, but from time to time, especially when doing operations one after another querying for a value you just set a moment before, will simply return NULL. This off course caused a lot of strange and hard to find errors.

In CRM it sometimes works like this:
SELECT Name FROM Table WHERE Id = 2
Result: AAA

UPDATE Table SET Name = ‘ZZZ’ WHERE Id = 2

SELECT Id FROM Table WHERE Name = ‘ZZZ’
Result: NULL

Off course when doing a standard FetchXML or QueryExpression everything is OK.

The solution – recreate the Data Context before each query – dataContext = new DataContext(), or as minimum before each query to an entity you used before. This will of course lower the performance a little, but let’s be honest 99,99% of the time is spend inside the query.

To be completely fair I have experienced similar issues with the “Portal Extensions” from CRM 4 but didn’t think Microsoft made CRM 2011 backward compatible in this matter Uśmiech

The SDK makes the impression that the LINQ queries are simply translated into QueryExpressions, apparently they are not.