0

In our backend app based on .NET 4.6, we use a lot of Linq To Sql compiled queries. Analyzing my application with dotMemory, I noticed that some of them have a reference to the (now disposed) DataContext with which the query was originally compiled. This reference never seems to go away.

The queries themselves are not complicated. Here is an example:

private static readonly Func<DataContext, int, IQueryable<bool>> _IsEditingAllowed_Anmeldung_CompiledQuery =
  CompiledQuery.Compile((DataContext db, int id) =>
      db.GetTable<PersonenAnmeldung>()
        .Where(p => p.Id1 == id)
        .Select(p => p.Status.AllowEdit));

The shortest path of such a query is as follows:

Retention path of DataContext

Static reference: StatusLogic._IsEditingAllowed_Anmeldung_CompiledQuery ->
Func<DataContext, Int32, IQueryable<Boolean>>._target ->
CompiledQuery.compiled ->
SqlProvider+CompiledQuery.queryInfos ->
SqlProvider+QueryInfo[1] at [0] ->
SqlProvider+QueryInfo.query ->
SqlSelect.selection ->
SqlColumnRef.sourceExpression ->
MethodCallExpressionN._arguments ->
TrueReadOnlyCollection<Expression>.list ->
Expression[2] at [0] ->
LinkedTableExpression.table ->
Table<Status>.context ->
DataContext

My question is, is there any known way to circumvent this problem? Is it a problem at all, other than filling up the memory with non-used data context?

Urs Meili
  • 618
  • 7
  • 19
  • 1
    But the query isn't compiled with a reference to a context *object*, only the type. You can define the query without ever instantiating a context. – Gert Arnold Mar 29 '16 at 18:59
  • no, the actual object instance is held in memory, not only a reference to the type. This can be seen in the memory profiler. It doesn't happen with all compiled queries, only with some. It seems to me that this happens as soon as there is a "linked table" in the query, such as p.Status.AllowEdit in my example. The problem is, the static definition will not store the DataContext instance, but as soon as I use the query (e.g. "var result=_IsEditingAllowed_Anmeldung_CompiledQuery(myDC,1000).FirstOrDefault()"), the current data context in "myDC" is stored in the compiled query. – Urs Meili Mar 30 '16 at 07:36

0 Answers0