Skip to content

Use case: Where filter

Christian Del Bianco edited this page Aug 22, 2018 · 10 revisions

Notification's filter condition based on record value can be achieve using the ways showed below.

Using SqlTableDependencyFilter

Let's assume a C# model as:

public class Category
{
        public int Id { get; set; }
        public string Code { get; set; }
        public decimal Price { get; set; }
}

After that, prepare your LINQ expression to filter data:

SqlTableDependency<Category> tableDependency = null;

Expression<Func<Category, bool>> filterExpression = p => p.Id == par1;

try
{
    tableDependency = new SqlTableDependency<Category>(
        ConnectionString, 
        filter: filterExpression);

    tableDependency.OnChanged += TableDependency_Changed;
    tableDependency.Start();

    Console.ReadKey();
}
finally
{
    tableDependency?.Dispose();
}

Code your ITableDependencyFilter's implementation

Translate method must return a valid T-SQL where condition.

public class CustomSqlTableDependencyFilter : ITableDependencyFilter
{
        private readonly int _id;

        public CustomSqlTableDependencyFilter(int id)
        {
            _id = id;
        }

        public string Translate()
        {
            return "[Id] = " + _id;
        }
}

Then assign your ITableDependencyFilter's implementation to SqlTableDependency's filter constructor property. The following code will produce a WHERE condition as Id >= 2 that will be added to the SqlTableDependency database table trigger:

SqlTableDependency<Category> tableDependency = null;

ITableDependencyFilter filterExpression = new CustomSqlTableDependencyFilter(2);

try
{
    tableDependency = new SqlTableDependency<Category>(
        ConnectionString, 
        filter: filterExpression);

    tableDependency.OnChanged += TableDependency_Changed;
    tableDependency.Start();

    Console.ReadKey();
}
finally
{
    tableDependency?.Dispose();
}