问题描述
如果数据库数据被更改,有没有办法让datagrid监听数据库并自动更新数据?我使用SQL Server数据库。
如果可能,我想使用Linq-2-SQL
那就是说,对于一个典型的n层应用来说,在很高的层次你需要: p>
(1)数据更改时通知中间层的一种方法。您可以在每个表中使用自定义代码触发器来触发某种通知(可能使用WCF和CLR存储过程),或者您可以使用对象。可能第二个会更好的工作。
(2)一种通知连接到该中间层的每个客户端的方法。假设您正在使用WCF,则需要使用可用的双工绑定之一,例如Net.TCP或HttpPollingDuplex(对于Silverlight)。您需要确保在客户端和服务器上均正确配置。您还需要手动跟踪哪些客户端可能对更新感兴趣,以便您可以知道要更新哪些客户端,并且当它们离开或超时时,您需要从该列表中删除它们。来自MS WCF团队的Tomek在他的,您可能需要调查。
(3)更新本地客户端模型和/或viewmodel和/或UI的机制一旦你从中间层获得了有所改变的通知。这比你想象的更复杂:在正常情况下,保持UI与数据模型的同步是很困难的,但是当数据模型可以从另一个方向发生变化时,它变得非常复杂。 / p>
这些通知背后的想法是非常简单的:但是,正确的获取所有详细信息可能会让您的调试方式进入夜晚。而那个从现在开始的两年之后的那个家伙,就会诅咒你的名字。
希望这有帮助。
Is there any way to have a datagrid listen to the database and automatically update the data if the database data is changed? I use a SQL Server database.
I'd like to use Linq-2-SQL if possible
Because @Slaggg asked: there are fairly straightforward ways of doing this, but they're almost certainly going to involve a lot of coding, it'll impact performance pretty significantly, and my strong suspicion is that it'll be more trouble than it's worth.
That said, for a typical n-tier application, at a very high level you'll need:
(1) A way to notify the middle tier when the data changes. You could use custom-code triggers inside each the table that fire off some sort of notification (perhaps using WCF and CLR stored procedures), or you could use a SqlDependency object. Probably the second would work better.
(2) A way to notify each client connected to that middle tier. Assuming that you're using WCF, you'll need to use one of the duplex bindings that are available, such as Net.TCP or HttpPollingDuplex (for Silverlight). You'll need to make sure this is configured correctly on both the client and the server. You'll also need to manually keep track of which clients might be interested in the update, so that you can know which ones to update, and you'll need to be able to remove them from that list when they go away or timeout. Tomek, from the MS WCF team, has some pretty good examples on his blog that you might want to investigate.
(3) A mechanism to update the local client's model and/or viewmodel and/or UI once you get the notification from the middle tier that something has changed. This is more complicated than you'd think: it's difficult enough to keep your UI in sync with your data model under normal circumstances, but it gets dramatically more complicated when that data model can be changing under you from the other direction as well.
The idea behind these sorts of notifications is straightforward enough: but getting all the details right is likely to keep you debugging way into the night. And the guy who has to support all this two years from now will curse your name.
Hope this helps.
这篇关于Datagrid不刷新已更改的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!