LINQ to SQL - 第二次运行方法不会返回自第一次以来发生的数据更改
我在数据上下文中创建了一个映射到 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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.
Don't share datacontexts between different page requests.