1

When setting the LoadOptions property on a LinqToSql DataContext, if the context has already returned results from another query, the exception "Setting load options is not allowed after results have been returned from a query" is thrown.

What I want to know is, is there a way to inspect the DataContext object to see if it has already returned results from a previous query?

Simon
  • 1,499
  • 3
  • 17
  • 23

3 Answers3

1

Well, it's not the DataContext than returns results per se, but a query. Queries are lazy loaded, which means they do not hit the database until their results are actually needed. For example, calling .ToList(), or looping through the result.

Still not exactly answering your question, but I recommend setting LoadOptions in the constructor of the DataContext -- or immediately after instantiating it. This should remove the mystery.

Matt Sherman
  • 8,298
  • 4
  • 37
  • 57
0

You typically wouldn't keep a DataContext around long enough to run into this issue. That class is designed to be cheap in regards to creation and destruction, so you would normally create a new DataContext object for a single unit of work and then dispose of it. Something like:

using( var db = new TestDataContext() )
{
    db.LoadOptions = CreateLoadOptions();
    var p = (from person in db.Persons
             where <someCondition>
             select p)
             .First();

    p.SomeProperty = someValue;
    db.SubmitChanges();
}   

I realize that doesn't technically answer your question, but I am not aware of a way to check whether or not a query has been executed on a DC short of setting a flag in your own code.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • I'll try to catch the exception first, if that doesn't work I'll break the unit of work up into smaller pieces as you suggest, thanks. – Simon Mar 14 '11 at 02:27
  • That's not the only problem that you can run into if you keep your DataContext around too long though, far from it. You should really just restructure the code to create these context objects on an as-needed basis. – Ed S. Mar 14 '11 at 02:46
0

I had the same problem.... the only way I found to avoid the exception (because you can't even reset the configuration) is to check if LoadOptions is null or not. If it's null I set the new option if it's not I create a new DataContext instance.

GRGodoi
  • 1,946
  • 2
  • 24
  • 38
  • I'm actually already doing a null check. I think what's happening is that even though LoadOptions is null, in my case because a stored procedure was called as the first query, the exception is still thrown. – Simon Mar 14 '11 at 02:19