开发者

How to tell if LinqToSql DataContext has previously returned results

开发者 https://www.devze.com 2023-02-16 09:53 出处:网络
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 a

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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号