如何判断 LinqToSql DataContext 之前是否已返回结果
在 LinqToSql DataContext
上设置 LoadOptions
属性时,如果上下文已从另一个查询返回结果,则会出现异常“Setting load options is not allowed after results were returned from抛出一个查询”。
我想知道的是,有没有办法检查 DataContext 对象以查看它是否已经返回了先前查询的结果?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,它返回的不是 DataContext 本身,而是一个查询。查询是延迟加载的,这意味着它们在实际需要结果之前不会访问数据库。例如,调用 .ToList(),或循环结果。
仍然没有完全回答您的问题,但我建议在 DataContext 的构造函数中设置 LoadOptions - 或者在实例化它之后立即设置。这应该可以消除谜团。
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.
您通常不会将 DataContext 保留足够长的时间来遇到此问题。该类被设计为在创建和销毁方面成本低廉,因此您通常会为单个工作单元创建一个新的 DataContext 对象,然后处理它。比如:
我意识到这在技术上并不能回答你的问题,但我不知道有什么方法可以检查查询是否已在 DC 上执行,而不需要在你自己的代码中设置标志。
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:
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.
我遇到了同样的问题......我发现避免异常的唯一方法(因为你甚至无法重置配置)是检查 LoadOptions 是否为空。如果它为空,我设置新选项,如果不是,我创建一个新的 DataContext 实例。
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.