Workaround for caching LINQ to SQL object identifiers and compiled query?

I came across what seems to be an error in linq for sql, where identifier caching does not work when executing primary key queries inside a compiled query.

I wrote the following example to demonstrate the use of identity caching. It makes only one database call on the first hit, each time after that it retrieves the client object from the data context cache.

for(int i=0; i<10; i++) { DataContext.GetTable<Customer>().Single(c=>c.Id == 1); } 

Unfortunately, when I convert the above sample into a compiled query, it cannot use the identifier cache and actually makes 10 calls in the database.

  for(int i=0; i<10; i++) { RetrieveCustomer(DataContext, 1); } private static readonly Func<DataContext, int, Customer> RetrieveCustomer = CompiledQuery.Compile((DataContext context, int id) => context.GetTable<Customer>().Single(c=>c.Id == id)); 

Has anyone else encountered this problem and created a workaround? It is imperative that server applications use compiled requests and identifier caching, so I hope this is a problem that someone else has worked with before!

+4
source share
2 answers

I ended up using a dirty hack to it, using reflection to call a private object method of a linq object called GetCachedEntity to force the cache. I did not have time to implement a cleaner solution, but for anyone interested in this topic, I would recommend implementing my own caching mechanism for this scenario.

+1
source

Looks like a mistake - there was a number in this area.

As a workflow, I would not create a compiled query for such a small / simple operation - the real benefit of a compiled query is large queries that take a lot of time to process in TSQL.

Update: this is a bug and has been resolved since it will not be fixed.

+2
source

All Articles