LINQ to SQL - 第二次运行方法不会返回自第一次以来发生的数据更改

发布于 2024-09-16 10:53:05 字数 609 浏览 3 评论 0原文

我在数据上下文中创建了一个映射到 SQL 存储过程的方法。该方法在 ASP.NET 应用程序中使用,并且在页面的生命周期中被调用两次。它在两种情况下返回相同的单个对象(即相同的主键)。

第一次调用后进行了一些数据更改,因此在第二次调用时,存储过程返回相同的记录,但具有不同的属性值。如果我使用调试器和 SQL Profiler,我可以绝对验证返回的记录在第一次和第二次调用之间具有相同的 PK 但不同的属性值。

但是,在第二次调用时,该方法返回的对象与第一次调用中返回的对象相同。就好像 LINQ 运行了存储过程,但随后完全忽略了结果,而是决定数据自第一次运行以来不会发生更改,因此它也可能返回发生的原始对象的副本坚持下去!

我尝试在调用我的方法之前立即将数据上下文的 ObjectTrackingEnabled 设置为 false,但这使我无法引用相关对象。

这是我用来调用该方法的代码:

Dim stl = _DataContext.GetMyStatus(SelectedUserID)
Dim st As MyStatus= stl.FirstOrDefault

我确实需要能够在页面的生命周期中多次调用该方法,并使其准确地反映数据库的当前状态,那么我该怎么做呢?

I have created a method in my data context that is mapped to a SQL stored procedure. The method is used in an ASP.NET application, and it is called twice in the lifecycle of a page. It returns the same single object in both cases (i.e. same primary key).

After the 1st call some data changes are made, so on the 2nd call the stored procedure returns the same record but with different property values. If I use the debugger and SQL Profiler I can verify absolutely that the record being returned has the same PK but different property values between the 1st and 2nd calls.

However, on the 2nd call the object returned by the method is identical to the object returned in the 1st call. It is as if LINQ has run the stored procedure but then totally ignored the results, deciding instead that the data couldn't have changed since the first time it was run, so it may as well return a copy of the original object that it happened to hang on to!

I have experimented with setting the datacontext's ObjectTrackingEnabled to false immediately before calling my method, but this stops me being able to reference related objects.

Here's the code I use to call the method:

Dim stl = _DataContext.GetMyStatus(SelectedUserID)
Dim st As MyStatus= stl.FirstOrDefault

I really need to be able to call this method more than once in the lifecycle of the page, and for it to accurately reflect the current state of the database, so how do I do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

胡渣熟男 2024-09-23 10:53:05

DataContext 为每个主键值生成一个实例。它在第一次看到记录时填充此单个实例,然后为将来使用该键的任何请求返回该实例。

如果要从数据库更新现有实例的值,请使用 Refresh 方法。

我确实需要能够在页面的生命周期中多次调用此方法,并使其准确反映数据库的当前状态。

不要在不同的页面请求之间共享数据上下文。

DataContext produces a single instance per primary key value. It populates this single instance the first time it sees the record, and then returns that instance for any future requests with that key.

If you want to update an existing instance's value from the database, use the Refresh method.

I really need to be able to call this method more than once in the lifecycle of the page, and for it to accurately reflect the current state of the database.

Don't share datacontexts between different page requests.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文