我正在开发一个具有 SQL 依赖特性的应用程序。当我执行应用程序时,未注册订阅。并且sys.dm_qn_subscriptions没有条目。我使用 SQL 探查器跟踪问题,我注意到订阅未注册,因为我没有收到消息1 – Subscription registered,而是收到3 – subscription fired以下通知消息:
<qnev:QNEvent xmlns:qnev="http://schemas.microsoft.com/SQL/Notifications/QueryNotificationProfiler"><qnev:EventText>subscription fired</qnev:EventText><qnev:SubscriptionID>0</qnev:SubscriptionID><qnev:NotificationMsg><qn:QueryNotification xmlns:qn="http://schemas.microsoft.com/SQL/Notifications/QueryNotification" id="0" type="subscribe" source="statement" info="set options" database_id="0" sid="0x01"><qn:Message>2c231f39-60c7-4a73-b575-617a791930f3;d06f0979-8f9b-490e-90ca-6042ab38d68c</qn:Message></qn:QueryNotification></qnev:NotificationMsg><qnev:BrokerDlg>2FAE7196-0E30-E411-8F82-0050569E473E</qnev:BrokerDlg></qnev:QNEvent>
当我检查它有以下信息:
Type: Subscription, Source: Statement and Info: set options
当我检查 msdn 的含义时,它说The connection options were not set appropriately when the command was submitted.
这是我正在使用的连接字符串
<add name="DefaultConnection" connectionString="Data Source=crmserver;Initial Catalog=crmdatabase;Persist Security Info=True;User ID=sa;Password=mypassword" />
以下是我正在使用的代码:
public List<Customer> GetLeadUpdates(SqlDependency dependency)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
var query = "SELECT id, name, salary FROM [dbo].[CustomerTest]";
connection.Open();
using (var command = new SqlCommand(query, connection))
{
command.Notification = null;
dependency.AddCommandDependency(command);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
var list = new List<Customer>();
while (reader.Read())
{
var customer = new Customer();
customer.Id = (int) reader["id"];
customer.Name = reader["name"].ToString();
customer.Salary = (int) reader["salary"];
list.Add(customer);
}
return list.OrderBy(p=>p.Id).ToList();
}
}
}
请让我知道我必须做什么才能成功注册订阅。我启用了服务代理并在连接字符串中使用“sa”凭据连接到 db,所以我想我不需要任何特定权限来订阅通知,因为 sa 是数据库的 dbo。