Linq-to-sql Compiled Query is returning result from different DataContext
- by Vladimir Kojic
Compiled query:
public static Func<OperationalDataContext, short, Machine>
QueryMachineById =
CompiledQuery.Compile((OperationalDataContext db, short machineID) =>
db.Machines.Where(m => m.MachineID == machineID).SingleOrDefault());
It looks like compiled query is caching Machine object and returning the same object even if query is called from new DataContext (I’m disposing DataContext in the service but I’m getting Machine from previous DataContext).
I use POCOs and XML mapping.
Revised:
It looks like compiled query is returning result from new data context and it is not using the one that I passed in compiled-query. Therefore I can not reuse returned object and link it to another object obtained from datacontext thru non compiled queries.
I’m using unit of work pattern :
// First Call
Using(new DataContext)
{
Machine from DataContext.Table == machine from cached query
}
// Do some work
// Second Call is failing
Using(new DataContext)
{
Machine from DataContext.Table <> machine from cached query
}