-
Notifications
You must be signed in to change notification settings - Fork 177
Use case: Code First Data Annotations to map model with database table
Christian Del Bianco edited this page Apr 23, 2018
·
3 revisions
In case our table has a name different from Model:
CREATE SCHEMA [Transaction]
GO
CREATE TABLE [Transaction].[Items] (
TransactionItemId uniqueidentifier NULL,
Description nvarchar(50) NOT NULL)
GO
We can use Code First Data Annotations to achieve mapping:
[Table("Items", Schema = "Transaction")]
public class Item
{
public Guid TransactionItemId { get; set; }
[Column("Description")]
public string Desc { get; set; }
}
In order to receive notifications containing record's values changed, inserted or deleted, the following code can be used:
using(var tableDependency = new SqlTableDependency<Item>(_connectionString))
{
tableDependency.OnChanged += TableDependency_Changed;
tableDependency.Start();
Console.WriteLine("Waiting for receiving notifications...");
Console.WriteLine("Press a key to stop");
Console.ReadKey();
}
...
...
void TableDependency_Changed(object sender, RecordChangedEventArgs<Item> e)
{
if (e.ChangeType != ChangeType.None)
{
var changedEntity = e.Entity;
Console.WriteLine("DML operation: " + e.ChangeType);
Console.WriteLine("ID: " + changedEntity.TransactionItemId);
Console.WriteLine("Description: " + changedEntity.Desc);
}
}