在互联网上搜索了一段时间后,我发现了这段代码,它触发了对数据库的基于linq的更改。它只触发一次,不提及或显示更改/删除/添加的内容,也不显示已删除的表。
static class GlobalNotifications
{
public static event OnChangeEventHandler OnChange;
public static void InitializeNotifications(string connectString)
{
// Initialize notifications
SqlDependency.Start(connectString);
// Create and register a new dependency
SqlDependency dependency = new SqlDependency();
dependency.OnChange += new OnChangeEventHandler(NotificationCallback);
System.Runtime.Remoting.Messaging.CallContext.SetData("MS.SqlDependencyCookie", dependency.Id);
}
internal static void NotificationCallback(object o, SqlNotificationEventArgs args)
{
OnChange.Invoke(o, args);
}
}
我是这样使用它的:
public partial class Nawa : Form
{
public Nawa()
{
InitializeComponent();
}
private void Nawa_Load(object sender, EventArgs e)
{
GlobalNotifications.InitializeNotifications("Server=GENISYSSERVER; Trusted_Connection=no;database=Maple_DBv1; user id=sa; password=Wc123Wc123");
GlobalNotifications.OnChange += new System.Data.SqlClient.OnChangeEventHandler(GlobalNotifications_OnChange);
}
void GlobalNotifications_OnChange(object sender, System.Data.SqlClient.SqlNotificationEventArgs e)
{
MessageBox.Show("Test");
}
private void button1_Click(object sender, EventArgs e)
{
using (DataClasses1DataContext dbcontext = new DataClasses1DataContext("Server=GENISYSSERVER; Trusted_Connection=no;database=Maple_DBv1; user id=sa; password=Wc123Wc123")) {
OrderFood random = dbcontext.OrderFoods.FirstOrDefault(id => id.ID == 10);
if (random != null) {
if (random.MenuID == 4)
random.MenuID = 1;
else
random.MenuID = 4;
dbcontext.SubmitChanges();
}
}
}
}
在这方面有人能帮忙吗?如何获得更改的详细信息、更改的类型、更改的表以及为什么只触发一次。此外,它如何只理解LINQ更改?它不会触发直接的变化等
参考:临时的喃喃抱怨
一个SQLDependency只会触发一次,您需要在它被触发后重新创建依赖。
OnChange事件触发一次,然后被消耗,所以你需要在它触发后再次连接事件。
Dan Miser - SqlDependency
我没有任何c#代码来演示如何处理这个问题,但我肯定有一些VB。. NET应该可以很好地工作,以便您提出自己的解决方案。
Private _permissionsDependency As SqlDependency
Private Sub doSubscribe()
_permissionsDependency = New SqlDependency(cmd.InnerCommand)
RemoveHandler _permissionsDependency.OnChange, AddressOf User_OnChange
AddHandler _permissionsDependency.OnChange, AddressOf User_OnChange
End Sub
Private Sub User_OnChange(ByVal sender As Object, ByVal e As System.Data.SqlClient.SqlNotificationEventArgs)
If _permissionsDependency IsNot Nothing Then RemoveHandler _permissionsDependency .OnChange, AddressOf User_OnChange
Select Case e.Info
Case SqlNotificationInfo.Delete
RaiseEvent UserDeleted(Me)
Case SqlNotificationInfo.Update
populateUser()
RaiseEvent UserUpdated(Me)
Case Else
End Select
End Sub
正如您所看到的,您可以通过查看e.Info
来找出发生了什么,这将允许您知道发生了什么(在我的示例中,我只查找删除和更新)。