Exemple #1
0
        public void Subscribe(IQueryable query)
        {
            if (null == _dependency)
            {
                //Get Query Object from IQuery Interface Value...
                _objectQuery = QueryExtension.GetObjectQuery <TEntity>(_context, query);

                //Get SQL connection string from Query Context...
                string connection = QueryExtension.GetConnectionString(_context);

                //Get SQL Command from Object Query...
                string commandString = QueryExtension.GetSqlString(_objectQuery);

                //Register SQL command
                using (SqlCommand command = new SqlCommand(commandString, new SqlConnection(connection)))
                {
                    //Open SQL Connection
                    command.Connection.Open();

                    command.Notification = null;

                    command.NotificationAutoEnlist = true;

                    // Create a dependency and associate it with the SqlCommand.
                    _dependency           = new SqlDependency(command);
                    _dependency.OnChange += dependency_OnChange;

                    // Execute the command.
                    SqlDataReader reader = command.ExecuteReader();
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Initializes a new instance of ImmediateNotificationRegister class.
        /// </summary>
        /// <param name="context">an instance of DbContext is used to get an ObjectQuery object</param>
        /// <param name="query">an instance of IQueryable is used to get ObjectQuery object, and then get
        /// _connection string and _command string to register SqlDependency nitification. </param>
        public SqlNotificationListener(DbContext context, IQueryable query)
        {
            try
            {
                this._iquery = query;
                _context     = context;

                // Get the ObjectQuery directly or convert the DbQuery to ObjectQuery.
                _oquery = QueryExtension.GetObjectQuery <TEntity>(context, _iquery);

                _connection = QueryExtension.GetSqlConnection(_oquery);
                _command    = QueryExtension.GetSqlCommand(_oquery, _connection);
            }
            catch (ArgumentException ex)
            {
                if (ex.ParamName == "context")
                {
                    throw new ArgumentException("Paramter cannot be null", nameof(context), ex);
                }

                throw new ArgumentException("Paramter cannot be null", nameof(query), ex);
            }
            catch (Exception ex)
            {
                throw new Exception(
                          "Fails to initialize a new instance of SqlNotificationListener class.", ex);
            }
        }