Skip to content

Use case: Custom map between model property and table column using ModelToTableMapper T

Christian Del Bianco edited this page May 22, 2018 · 4 revisions

When model has properties with different name from table's column, we can use ModelToTableMapper for mapping:

Assuming a database table as:

CREATE TABLE [Customer] (
	[Id] [int] IDENTITY(1, 1) NOT NULL,
	[First Name] [varchar](50) NULL,
	[Last Name] [varchar](50) NULL)

Assuming a C# model as:

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }

In order to receive notifications containing record's values changed, inserted or deleted, the following code can be used:

var mapper = new ModelToTableMapper<Customer>();
mapper.AddMapping(c => c.Name, "First Name");
mapper.AddMapping(c => c.Surname, "Last Name");

var tableDependency = new SqlTableDependency<Customer>(
    connectionString, 
    mapper: mapper);

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

This setting override Code First Data Annotations.