Search code examples
microsoft-dynamicsdynamics-crm-2015

CRM 2015 Microsoft.Xrm.Sdk: Unexpected results in second CreateQuery call


Microsoft.Xrm.Sdk, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

var ctx = new ServiceContext(...);

var result1 = (from f in ctx.CreateQuery<aEntity>()
               where f.field1 == "x"
               select new { f.Id, f.field2 }).ToList();

var result2 = (from f in ctx.CreateQuery<aEntity>()
               where f.field1 == "x"
               select f.field1).First();

result2 returns null! After adding f.field1 to the select clause in the first query result2 returns "x". It looks like a internal columnset is created and used in the context of the second call. Looking at the SQL Server trace of both calls we see the expected select-from queries based on the C# code. The returned second result is not expected. Can someone explain this behaviour?


Solution

  • As for me it looks like a caching functionality and it's on the side of CRM because as you mentioned SQL queries were correct. I had the same issue in my applications when tried to make two consecutive queries for the same entity record but selected two different fields, the second request always returned NULL.
    Here are workarounds that I use when work with the ServiceContext:

    1. Simple one: always retrieve an entity with all fields (without select statement) (even if I want it or not)
    2. or create a service context with disabled caching


    Right now I try to use the ServiceContext as less as possible replacing it with QueryBase expressions (even if I love to use LINQ).